-- Ground Zero Database Purge Script
-- Deletes ALL test users and related data

BEGIN;

-- 1. First, identify and count test users
SELECT 'Test users to delete:' as info;
SELECT id, email 
FROM identity.users 
WHERE (
    email ILIKE '%test%' OR 
    email ILIKE '%noreply%' OR 
    email ILIKE '%profibot%' OR 
    email ILIKE '%example.com' OR 
    email ILIKE '%@gmail.com'
) AND is_deleted = false
ORDER BY id;

-- 2. Delete from gamification tables (if they exist)
DO $$ 
BEGIN
    -- Check if table exists before deleting
    IF EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'gamification' AND table_name = 'user_stats') THEN
        DELETE FROM gamification.user_stats 
        WHERE user_id IN (
            SELECT id FROM identity.users 
            WHERE (
                email ILIKE '%test%' OR 
                email ILIKE '%noreply%' OR 
                email ILIKE '%profibot%' OR 
                email ILIKE '%example.com' OR 
                email ILIKE '%@gmail.com'
            ) AND is_deleted = false
        );
        RAISE NOTICE 'Deleted from gamification.user_stats';
    END IF;
    
    IF EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'gamification' AND table_name = 'points_ledger') THEN
        DELETE FROM gamification.points_ledger 
        WHERE user_id IN (
            SELECT id FROM identity.users 
            WHERE (
                email ILIKE '%test%' OR 
                email ILIKE '%noreply%' OR 
                email ILIKE '%profibot%' OR 
                email ILIKE '%example.com' OR 
                email ILIKE '%@gmail.com'
            ) AND is_deleted = false
        );
        RAISE NOTICE 'Deleted from gamification.points_ledger';
    END IF;
END $$;

-- 3. Delete wallets (must be done before users due to FK constraint)
DELETE FROM identity.wallets 
WHERE user_id IN (
    SELECT id FROM identity.users 
    WHERE (
        email ILIKE '%test%' OR 
        email ILIKE '%noreply%' OR 
        email ILIKE '%profibot%' OR 
        email ILIKE '%example.com' OR 
        email ILIKE '%@gmail.com'
    ) AND is_deleted = false
);

-- 4. Finally delete the test users
DELETE FROM identity.users 
WHERE (
    email ILIKE '%test%' OR 
    email ILIKE '%noreply%' OR 
    email ILIKE '%profibot%' OR 
    email ILIKE '%example.com' OR 
    email ILIKE '%@gmail.com'
) AND is_deleted = false;

-- 5. Delete orphaned persons
DELETE FROM identity.persons 
WHERE NOT EXISTS (
    SELECT 1 FROM identity.users 
    WHERE users.person_id = persons.id
);

-- 6. Show results
SELECT 'Purge completed. Summary:' as info;
SELECT 
    (SELECT COUNT(*) FROM identity.users WHERE email ILIKE '%test%' AND is_deleted = false) as remaining_test_users,
    (SELECT COUNT(*) FROM identity.users WHERE email ILIKE '%noreply%' AND is_deleted = false) as remaining_noreply_users,
    (SELECT COUNT(*) FROM identity.users WHERE email ILIKE '%profibot%' AND is_deleted = false) as remaining_profibot_users;

COMMIT;