-- =====================================================
-- ROLLBACK SCRIPT
-- Date: February 15, 2026
-- Version: 2.2.0 → 2.1.0
-- Description: Rollback per-company permissions changes
-- =====================================================
-- 
-- ⚠️  WARNING: 
-- 1. This will remove per-company permission columns
-- 2. You will lose any per-company permission configurations
-- 3. Only run this if deployment fails or you need to revert
-- 4. Backup your database before running
--
-- Usage:
--   psql -U your_db_user -d your_database_name -f rollback_2026_02_15.sql
--
-- =====================================================

\echo ''
\echo '=============================================='
\echo 'Starting Rollback: 2.2.0 → 2.1.0'
\echo 'Date: February 15, 2026'
\echo '=============================================='
\echo ''
\echo '⚠️  WARNING: This will remove per-company permissions!'
\echo '⚠️  Press Ctrl+C to cancel within 5 seconds...'
\echo ''

-- Give time to cancel
SELECT pg_sleep(5);

BEGIN;

\echo 'Starting rollback process...'

-- Remove composite index
DROP INDEX IF EXISTS idx_uc_user_company;
\echo '✓ Removed composite index idx_uc_user_company'

-- Remove permission columns
ALTER TABLE user_companies DROP COLUMN IF EXISTS can_add_edit;
\echo '✓ Removed can_add_edit column'

ALTER TABLE user_companies DROP COLUMN IF EXISTS can_delete;
\echo '✓ Removed can_delete column'

-- Verify rollback
DO $$
DECLARE
    col_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO col_count
    FROM information_schema.columns
    WHERE table_name = 'user_companies' 
    AND column_name IN ('can_add_edit', 'can_delete');
    
    IF col_count = 0 THEN
        RAISE NOTICE '✓ Rollback verification successful';
    ELSE
        RAISE EXCEPTION 'Rollback verification failed: Found % columns still present', col_count;
    END IF;
END $$;

\echo ''
\echo '=============================================='
\echo 'Rollback completed successfully!'
\echo 'System reverted to Version 2.1.0'
\echo '=============================================='
\echo ''
\echo 'Next steps:'
\echo '1. Clear application cache'
\echo '2. Test application functionality'
\echo '3. Review error logs to identify deployment issue'
\echo ''

COMMIT;

\echo '✓ Transaction committed successfully'

