-- Deduplicate Tipos Eventos (Case Insensitive)
-- 1. Update references to point to the "Keep" version (initcap/first one)
-- 2. Delete the duplicates

DO $$
DECLARE
    r RECORD;
    keep_id UUID;
BEGIN
    -- Iterate over duplicates in tipos_eventos
    FOR r IN 
        SELECT lower(trim(nome)) as norm_name, regiao 
        FROM tipos_eventos 
        GROUP BY lower(trim(nome)), regiao 
        HAVING count(*) > 1
    LOOP
        -- Pick the one to keep (e.g., the one that starts with Uppercase, or just the first created)
        -- We prefer the one that is NOT all lowercase if possible.
        SELECT id INTO keep_id 
        FROM tipos_eventos 
        WHERE lower(trim(nome)) = r.norm_name AND regiao = r.regiao
        ORDER BY nome DESC -- Assuming Uppercase comes before lowercase in ASCII? No, 'B' < 'b'. But 'Baile' < 'baile'. 
        -- Actually, 'B' (66) < 'b' (98). So 'Baile' is smaller.
        -- Let's sort by nome ASC to pick 'Baile' over 'baile'.
        LIMIT 1;
        
        RAISE NOTICE 'Merging duplicate % in % -> Keeping %', r.norm_name, r.regiao, keep_id;

        -- Update FK references in agenda
        UPDATE agenda SET tipo_evento_id = keep_id 
        WHERE tipo_evento_id IN (
            SELECT id FROM tipos_eventos 
            WHERE lower(trim(nome)) = r.norm_name AND regiao = r.regiao AND id != keep_id
        );
        
        -- Update FK references in precos_tipos_eventos (if any)
        UPDATE precos_tipos_eventos SET tipo_evento_id = keep_id 
        WHERE tipo_evento_id IN (
            SELECT id FROM tipos_eventos 
            WHERE lower(trim(nome)) = r.norm_name AND regiao = r.regiao AND id != keep_id
        );

        -- Delete the others
        DELETE FROM tipos_eventos 
        WHERE lower(trim(nome)) = r.norm_name 
          AND regiao = r.regiao 
          AND id != keep_id;
          
    END LOOP;
END $$;
