-- IDs de Dedução baseados nos códigos criados pelo Initializer
DO $$
DECLARE
    v_irps_id UUID;
    v_inps_id UUID;
    v_selo_id UUID;
BEGIN
    -- Obter IDs
    SELECT id INTO v_irps_id FROM deduction_type WHERE code = 'IRPS';
    SELECT id INTO v_inps_id FROM deduction_type WHERE code = 'INPS';
    SELECT id INTO v_selo_id FROM deduction_type WHERE code = 'SELO';

    -- 1. Regras Globais (Se não existirem)
    IF v_inps_id IS NOT NULL THEN
        INSERT INTO global_deduction_rule (id, deduction_type_id, percentage, valid_from, active, created_at, updated_at)
        VALUES (gen_random_uuid(), v_inps_id, 0.07, '2024-01-01', true, now(), now())
        ON CONFLICT DO NOTHING;
    END IF;

    IF v_selo_id IS NOT NULL THEN
        INSERT INTO global_deduction_rule (id, deduction_type_id, percentage, valid_from, active, created_at, updated_at)
        VALUES (gen_random_uuid(), v_selo_id, 0.003, '2024-01-01', true, now(), now())
        ON CONFLICT DO NOTHING;
    END IF;

    -- 2. Escalões de IRPS
    IF v_irps_id IS NOT NULL THEN
        -- Limpar escalões antigos para garantir a nova tabela
        DELETE FROM tax_bracket WHERE deduction_type_id = v_irps_id;

        -- Faixa 1: Isento (0 - 50.000)
        INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
        VALUES (gen_random_uuid(), v_irps_id, 0, 50000, 0, 0, '2024-01-01', now(), now());

        -- Faixa 2: 10% (50.001 - 150.000)
        INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
        VALUES (gen_random_uuid(), v_irps_id, 50001, 150000, 0.10, 5000, '2024-01-01', now(), now());

        -- Faixa 3: 15% (150.001 - 250.000)
        INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
        VALUES (gen_random_uuid(), v_irps_id, 150001, 250000, 0.15, 12500, '2024-01-01', now(), now());

        -- Faixa 4: 20% (250.001 - 500.000)
        INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
        VALUES (gen_random_uuid(), v_irps_id, 250001, 500000, 0.20, 25000, '2024-01-01', now(), now());

        -- Faixa 5: 25% (Acima de 500.000)
        INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
        VALUES (gen_random_uuid(), v_irps_id, 500001, NULL, 0.25, 50000, '2024-01-01', now(), now());
    END IF;
END $$;
