-- Timezone Migration Rollback Script
-- Rollback: 20250729000001_timezone_conversion_est_to_utc_rollback.sql
--
-- This script will revert the timezone conversion migration by restoring
-- the original EST-masquerading-as-UTC timestamps from backup tables.
--
-- WARNING: Only run this if the migration needs to be reverted!
-- This will restore the original problematic timezone storage.

-- Start transaction for atomic rollback
BEGIN;

-- ================================
-- VALIDATION CHECKS
-- ================================

-- Verify backup tables exist
DO $$
DECLARE
    backup_count INTEGER;
BEGIN
    -- Check if backup tables exist
    SELECT COUNT(*) INTO backup_count
    FROM information_schema.tables 
    WHERE table_name IN (
        'events_timezone_backup',
        'pending_events_timezone_backup', 
        'bulletins_timezone_backup',
        'users_timezone_backup',
        'church_config_timezone_backup',
        'schedules_timezone_backup',
        'bible_verses_timezone_backup',
        'app_versions_timezone_backup'
    );
    
    IF backup_count < 8 THEN
        RAISE EXCEPTION 'Backup tables not found! Cannot proceed with rollback. Expected 8 backup tables, found %.', backup_count;
    END IF;
    
    RAISE NOTICE 'Backup tables verified. Proceeding with rollback...';
END $$;

-- ================================
-- PRE-ROLLBACK VALIDATION SAMPLES
-- ================================

-- Show current state before rollback
DO $$
DECLARE
    sample_record RECORD;
BEGIN
    RAISE NOTICE '========================================';
    RAISE NOTICE 'PRE-ROLLBACK CURRENT STATE (UTC times)';
    RAISE NOTICE '========================================';
    
    FOR sample_record IN 
        SELECT 
            'events' as table_name,
            id::text as record_id,
            start_time as current_utc_time,
            start_time AT TIME ZONE 'America/New_York' as current_ny_display
        FROM events 
        WHERE start_time IS NOT NULL 
        LIMIT 3
    LOOP
        RAISE NOTICE 'Table: %, ID: %', sample_record.table_name, sample_record.record_id;
        RAISE NOTICE '  Current UTC: %', sample_record.current_utc_time;
        RAISE NOTICE '  Current NY Display: %', sample_record.current_ny_display;
        RAISE NOTICE '----------------------------------------';
    END LOOP;
END $$;

-- ================================
-- ROLLBACK EVENTS TABLE
-- ================================

RAISE NOTICE 'Rolling back events table...';

UPDATE events 
SET 
    start_time = backup.original_start_time,
    end_time = backup.original_end_time,
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM events_timezone_backup backup
WHERE events.id = backup.id;

-- ================================
-- ROLLBACK PENDING_EVENTS TABLE  
-- ================================

RAISE NOTICE 'Rolling back pending_events table...';

UPDATE pending_events 
SET 
    start_time = backup.original_start_time,
    end_time = backup.original_end_time,
    submitted_at = backup.original_submitted_at,
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM pending_events_timezone_backup backup
WHERE pending_events.id = backup.id;

-- ================================
-- ROLLBACK BULLETINS TABLE
-- ================================

RAISE NOTICE 'Rolling back bulletins table...';

UPDATE bulletins 
SET 
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM bulletins_timezone_backup backup
WHERE bulletins.id = backup.id;

-- ================================  
-- ROLLBACK USERS TABLE
-- ================================

RAISE NOTICE 'Rolling back users table...';

UPDATE users 
SET 
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM users_timezone_backup backup
WHERE users.id = backup.id;

-- ================================
-- ROLLBACK CHURCH_CONFIG TABLE
-- ================================

RAISE NOTICE 'Rolling back church_config table...';

UPDATE church_config 
SET 
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM church_config_timezone_backup backup
WHERE church_config.id = backup.id;

-- ================================
-- ROLLBACK SCHEDULES TABLE
-- ================================

RAISE NOTICE 'Rolling back schedules table...';

UPDATE schedules 
SET 
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM schedules_timezone_backup backup
WHERE schedules.id = backup.id;

-- ================================
-- ROLLBACK BIBLE_VERSES TABLE
-- ================================

RAISE NOTICE 'Rolling back bible_verses table...';

UPDATE bible_verses 
SET 
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM bible_verses_timezone_backup backup
WHERE bible_verses.id = backup.id;

-- ================================
-- ROLLBACK APP_VERSIONS TABLE
-- ================================

RAISE NOTICE 'Rolling back app_versions table...';

UPDATE app_versions 
SET 
    created_at = backup.original_created_at,
    updated_at = backup.original_updated_at
FROM app_versions_timezone_backup backup
WHERE app_versions.id = backup.id;

-- ================================
-- POST-ROLLBACK VALIDATION
-- ================================

-- Show state after rollback (should match original pre-migration state)
DO $$
DECLARE
    sample_record RECORD;
    events_count INTEGER;
    pending_count INTEGER;
BEGIN
    RAISE NOTICE '========================================';
    RAISE NOTICE 'POST-ROLLBACK STATE (Back to EST-as-UTC)';
    RAISE NOTICE '========================================';
    
    FOR sample_record IN 
        SELECT 
            'events' as table_name,
            id::text as record_id,
            start_time as restored_est_time,
            start_time AT TIME ZONE 'America/New_York' as restored_display
        FROM events 
        WHERE start_time IS NOT NULL 
        LIMIT 3
    LOOP
        RAISE NOTICE 'Table: %, ID: %', sample_record.table_name, sample_record.record_id;
        RAISE NOTICE '  Restored EST-as-UTC: %', sample_record.restored_est_time;
        RAISE NOTICE '  Display Time: %', sample_record.restored_display;
        RAISE NOTICE '----------------------------------------';
    END LOOP;
    
    -- Show rollback statistics
    SELECT COUNT(*) INTO events_count FROM events WHERE start_time IS NOT NULL;
    SELECT COUNT(*) INTO pending_count FROM pending_events WHERE start_time IS NOT NULL;
    
    RAISE NOTICE '========================================';
    RAISE NOTICE 'ROLLBACK STATISTICS';
    RAISE NOTICE '========================================';
    RAISE NOTICE 'Events rolled back: %', events_count;
    RAISE NOTICE 'Pending events rolled back: %', pending_count;
    RAISE NOTICE '========================================';
END $$;

-- ================================
-- UPDATE MIGRATION LOG
-- ================================

-- Record the rollback in migration log
INSERT INTO migration_log (migration_name, description, executed_at)
VALUES (
    '20250729000001_timezone_conversion_est_to_utc_ROLLBACK',
    'Rolled back timezone conversion migration. Restored original EST-masquerading-as-UTC timestamps from backup tables.',
    NOW()
);

-- ================================
-- CLEANUP OPTIONS (commented out for safety)
-- ================================

-- Uncomment the following section if you want to drop backup tables after successful rollback
-- WARNING: This will permanently delete the backup tables!

/*
RAISE NOTICE 'Cleaning up backup tables...';

DROP TABLE IF EXISTS events_timezone_backup;
DROP TABLE IF EXISTS pending_events_timezone_backup;
DROP TABLE IF EXISTS bulletins_timezone_backup;
DROP TABLE IF EXISTS users_timezone_backup;
DROP TABLE IF EXISTS church_config_timezone_backup;
DROP TABLE IF EXISTS schedules_timezone_backup;
DROP TABLE IF EXISTS bible_verses_timezone_backup;
DROP TABLE IF EXISTS app_versions_timezone_backup;

RAISE NOTICE 'Backup tables cleaned up.';
*/

-- ================================
-- ROLLBACK COMPLETE LOG
-- ================================

RAISE NOTICE '========================================';
RAISE NOTICE 'TIMEZONE MIGRATION ROLLBACK COMPLETED';
RAISE NOTICE 'Rollback: 20250729000001_timezone_conversion_est_to_utc_rollback';
RAISE NOTICE 'Executed at: %', NOW();
RAISE NOTICE '========================================';
RAISE NOTICE 'STATUS: All timestamps restored to original EST-as-UTC format';
RAISE NOTICE 'WARNING: This reverts to the problematic timezone storage!';
RAISE NOTICE 'BACKUP TABLES: Preserved for future migrations (not dropped)';
RAISE NOTICE '========================================';

-- Commit the rollback transaction
COMMIT;