-- ============================================================================
-- SCRIPT COMPLEMENTAR DE DADOS PARA TESTES FUNCIONAIS COMPLETOS
-- Adiciona dados necessários para testar fluxos completos do sistema
-- ============================================================================
-- 
-- Este script complementa insert_all_test_data.sql adicionando:
-- - Períodos de folha adicionais
-- - Execuções de folha completas (COMPLETED)
-- - Itens de folha completos com todos os cálculos
-- - Execuções orçamentárias (COMMITMENT, LIQUIDATION, PAYMENT)
-- - Lotes de pagamento
-- - Ordens de pagamento
-- - Confirmações de pagamento do tesouro
-- - Dados para testar fluxos end-to-end
--
-- IMPORTANTE: Execute insert_all_test_data.sql primeiro!

DO $$
DECLARE
    -- IDs existentes
    v_min_financas UUID;
    v_min_saude UUID;
    v_min_educacao UUID;
    v_ou_tesouro UUID;
    v_ou_orcamento UUID;
    v_ou_hospital UUID;
    v_ou_escola UUID;
    
    -- Agentes
    v_agent_amilcar UUID;
    v_agent_francisca UUID;
    v_agent_joao UUID;
    v_agent_maria UUID;
    v_agent_samba UUID;
    
    -- Ano Fiscal e Linhas Orçamentais
    v_fy_2025 UUID;
    v_bl_financas UUID;
    v_bl_saude UUID;
    v_bl_educacao UUID;
    
    -- Tipos de Proventos e Descontos
    v_earning_vencimento UUID;
    v_earning_abono UUID;
    v_deduction_inps UUID;
    v_deduction_irps UUID;
    v_deduction_selo UUID;
    
    -- Contas Bancárias
    v_account_amilcar UUID;
    v_account_francisca UUID;
    v_account_joao UUID;
    v_account_maria UUID;
    v_account_samba UUID;
    
    -- Períodos de Folha
    v_period_jan2025 UUID;
    v_period_fev2025 UUID;
    v_period_mar2025 UUID;
    
    -- Execuções de Folha
    v_payroll_run_jan_completed UUID;
    v_payroll_run_fev_completed UUID;
    v_payroll_run_mar_pending UUID;
    
    -- Lotes de Pagamento
    v_batch_jan UUID;
    v_batch_fev UUID;
    
    -- Usuário Admin
    v_user_admin UUID;
    
BEGIN
    RAISE NOTICE '=== INICIANDO CARGA DE DADOS PARA TESTES FUNCIONAIS ===';
    
    -- ========================================================================
    -- OBTER IDs EXISTENTES
    -- ========================================================================
    SELECT id INTO v_min_financas FROM ministry WHERE code = 'MIN-001';
    SELECT id INTO v_min_saude FROM ministry WHERE code = 'MIN-002';
    SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MIN-003';
    
    SELECT id INTO v_ou_tesouro FROM org_unit WHERE code = 'UO-001';
    SELECT id INTO v_ou_orcamento FROM org_unit WHERE code = 'UO-002';
    SELECT id INTO v_ou_hospital FROM org_unit WHERE code = 'UO-003';
    SELECT id INTO v_ou_escola FROM org_unit WHERE code = 'UO-004';
    
    SELECT id INTO v_agent_amilcar FROM agents WHERE matricula = '2020/001';
    SELECT id INTO v_agent_francisca FROM agents WHERE matricula = '2021/045';
    SELECT id INTO v_agent_joao FROM agents WHERE matricula = '2019/089';
    SELECT id INTO v_agent_maria FROM agents WHERE matricula = '2022/112';
    SELECT id INTO v_agent_samba FROM agents WHERE matricula = '2024/201';
    
    SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
    
    SELECT id INTO v_bl_financas FROM budget_line WHERE code = '2025-MINFIN-311100';
    SELECT id INTO v_bl_saude FROM budget_line WHERE code = '2025-MINSAUDE-311100';
    SELECT id INTO v_bl_educacao FROM budget_line WHERE code = '2025-MINEDU-311100';
    
    SELECT id INTO v_earning_vencimento FROM earning_type WHERE code = 'VENC-BASE';
    SELECT id INTO v_earning_abono FROM earning_type WHERE code = 'ABONO-FAM';
    SELECT id INTO v_deduction_inps FROM deduction_type WHERE code = 'INPS';
    SELECT id INTO v_deduction_irps FROM deduction_type WHERE code = 'IRPS';
    SELECT id INTO v_deduction_selo FROM deduction_type WHERE code = 'SELO';
    
    SELECT id INTO v_account_amilcar FROM agent_bank_account WHERE agent_id = v_agent_amilcar AND is_primary = true;
    SELECT id INTO v_account_francisca FROM agent_bank_account WHERE agent_id = v_agent_francisca AND is_primary = true;
    SELECT id INTO v_account_joao FROM agent_bank_account WHERE agent_id = v_agent_joao AND is_primary = true;
    
    SELECT id INTO v_user_admin FROM user_account WHERE username = 'admin';
    
    -- Criar contas bancárias para agentes que não têm
    IF v_account_maria IS NULL THEN
        INSERT INTO agent_bank_account (id, agent_id, bank, account_number, branch_code, is_primary, created_at, updated_at)
        VALUES ('00110001-0000-0000-0000-000000000000', v_agent_maria, 'BCEAO', '4567890123', '004', true, now(), now())
        RETURNING id INTO v_account_maria;
    END IF;
    
    IF v_account_samba IS NULL THEN
        INSERT INTO agent_bank_account (id, agent_id, bank, account_number, branch_code, is_primary, created_at, updated_at)
        VALUES ('00110002-0000-0000-0000-000000000000', v_agent_samba, 'BRS', '5678901234', '005', true, now(), now())
        RETURNING id INTO v_account_samba;
    END IF;
    
    -- ========================================================================
    -- PERÍODOS DE FOLHA ADICIONAIS
    -- ========================================================================
    INSERT INTO payroll_period (id, fiscal_year, month, start_date, end_date, status, created_at, updated_at) VALUES
    ('00120001-0000-0000-0000-000000000000', 2025, 2, '2025-02-01', '2025-02-28', 'OPEN', now(), now()),
    ('00120002-0000-0000-0000-000000000000', 2025, 3, '2025-03-01', '2025-03-31', 'OPEN', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    SELECT id INTO v_period_jan2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 1;
    SELECT id INTO v_period_fev2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 2;
    SELECT id INTO v_period_mar2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 3;
    
    -- ========================================================================
    -- EXECUÇÕES DE FOLHA COMPLETAS
    -- ========================================================================
    -- Janeiro - COMPLETED (para gerar ordens de pagamento)
    INSERT INTO payroll_run (id, period_id, ministry_id, org_unit_id, run_type, status, created_at, updated_at, created_by) VALUES
    ('00130001-0000-0000-0000-000000000000', v_period_jan2025, v_min_financas, v_ou_tesouro, 'REGULAR', 'COMPLETED', now(), now(), v_user_admin)
    ON CONFLICT (id) DO NOTHING;
    
    SELECT id INTO v_payroll_run_jan_completed FROM payroll_run WHERE id = '00130001-0000-0000-0000-000000000000';
    
    -- Fevereiro - COMPLETED
    INSERT INTO payroll_run (id, period_id, ministry_id, org_unit_id, run_type, status, created_at, updated_at, created_by) VALUES
    ('00130002-0000-0000-0000-000000000000', v_period_fev2025, v_min_financas, v_ou_tesouro, 'REGULAR', 'COMPLETED', now(), now(), v_user_admin)
    ON CONFLICT (id) DO NOTHING;
    
    SELECT id INTO v_payroll_run_fev_completed FROM payroll_run WHERE id = '00130002-0000-0000-0000-000000000000';
    
    -- Março - PENDING (para testar validações)
    INSERT INTO payroll_run (id, period_id, ministry_id, org_unit_id, run_type, status, created_at, updated_at, created_by) VALUES
    ('00130003-0000-0000-0000-000000000000', v_period_mar2025, v_min_financas, v_ou_tesouro, 'REGULAR', 'PENDING', now(), now(), v_user_admin)
    ON CONFLICT (id) DO NOTHING;
    
    SELECT id INTO v_payroll_run_mar_pending FROM payroll_run WHERE id = '00130003-0000-0000-0000-000000000000';
    
    -- ========================================================================
    -- ITENS DE FOLHA COMPLETOS (Janeiro - COMPLETED)
    -- Com todos os cálculos: Vencimento, Abono, INPS, IRPS, Selo
    -- ========================================================================
    -- Amilcar Cabral - Vencimento Base: 600.000
    INSERT INTO payroll_item (
        id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
        description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
    ) VALUES
    -- Vencimento Base
    ('00140001-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'EARNING', v_earning_vencimento, NULL,
     'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_financas, now(), now()),
    -- Abono de Família (2 dependentes)
    ('00140002-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'EARNING', v_earning_abono, NULL,
     'Abono de Família (2 dep.)', 2000.00, 2.00, 4000.00, v_bl_financas, now(), now()),
    -- INPS 7% sobre 604.000 = 42.280
    ('00140003-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_inps,
     'INPS 7%', 42280.00, 1.00, 42280.00, NULL, now(), now()),
    -- Selo 0.3% sobre 604.000 = 1.812
    ('00140004-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_selo,
     'Imposto de Selo 0.3%', 1812.00, 1.00, 1812.00, NULL, now(), now()),
    -- IRPS: Base = 604.000 - 42.280 = 561.720
    -- Faixa 50001-150000: (561.720 - 50.000) * 10% - 5.000 = 51.172 - 5.000 = 46.172
    ('00140005-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_irps,
     'IRPS', 46172.00, 1.00, 46172.00, NULL, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- Francisca Pereira - Vencimento Base: 550.000
    INSERT INTO payroll_item (
        id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
        description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
    ) VALUES
    -- Vencimento Base
    ('00140006-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'EARNING', v_earning_vencimento, NULL,
     'Vencimento Base', 550000.00, 1.00, 550000.00, v_bl_financas, now(), now()),
    -- Abono de Família (1 dependente)
    ('00140007-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'EARNING', v_earning_abono, NULL,
     'Abono de Família (1 dep.)', 2000.00, 1.00, 2000.00, v_bl_financas, now(), now()),
    -- INPS 7% sobre 552.000 = 38.640
    ('00140008-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'DEDUCTION', NULL, v_deduction_inps,
     'INPS 7%', 38640.00, 1.00, 38640.00, NULL, now(), now()),
    -- Selo 0.3% sobre 552.000 = 1.656
    ('00140009-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'DEDUCTION', NULL, v_deduction_selo,
     'Imposto de Selo 0.3%', 1656.00, 1.00, 1656.00, NULL, now(), now()),
    -- IRPS: Base = 552.000 - 38.640 = 513.360
    -- Faixa 50001-150000: (513.360 - 50.000) * 10% - 5.000 = 46.336 - 5.000 = 41.336
    ('0014000a-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'DEDUCTION', NULL, v_deduction_irps,
     'IRPS', 41336.00, 1.00, 41336.00, NULL, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- João Vieira - Vencimento Base: 600.000 (Saúde)
    INSERT INTO payroll_item (
        id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
        description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
    ) VALUES
    ('0014000b-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'EARNING', v_earning_vencimento, NULL,
     'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_saude, now(), now()),
    ('0014000c-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'EARNING', v_earning_abono, NULL,
     'Abono de Família (3 dep.)', 2000.00, 3.00, 6000.00, v_bl_saude, now(), now()),
    ('0014000d-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'DEDUCTION', NULL, v_deduction_inps,
     'INPS 7%', 42420.00, 1.00, 42420.00, NULL, now(), now()),
    ('0014000e-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'DEDUCTION', NULL, v_deduction_selo,
     'Imposto de Selo 0.3%', 1818.00, 1.00, 1818.00, NULL, now(), now()),
    ('0014000f-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'DEDUCTION', NULL, v_deduction_irps,
     'IRPS', 46178.00, 1.00, 46178.00, NULL, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- EXECUÇÕES ORÇAMENTÁRIAS (Budget Execution)
    -- COMMITMENT: Compromisso quando a folha é gerada
    -- LIQUIDATION: Liquidação quando a folha é processada
    -- PAYMENT: Pagamento quando o tesouro confirma
    -- ========================================================================
    -- COMMITMENT - Janeiro (compromisso inicial)
    INSERT INTO budget_execution (
        id, budget_line_id, period_id, movement_type, amount, source_module, reference_id, created_at, updated_at
    ) VALUES
    ('00150001-0000-0000-0000-000000000000', v_bl_financas, 202501, 'COMMITMENT', 1156000.00, 'RH', v_payroll_run_jan_completed, now(), now()),
    ('00150002-0000-0000-0000-000000000000', v_bl_saude, 202501, 'COMMITMENT', 606000.00, 'RH', v_payroll_run_jan_completed, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- LIQUIDATION - Janeiro (liquidação após processamento)
    INSERT INTO budget_execution (
        id, budget_line_id, period_id, movement_type, amount, source_module, reference_id, created_at, updated_at
    ) VALUES
    ('00150003-0000-0000-0000-000000000000', v_bl_financas, 202501, 'LIQUIDATION', 1156000.00, 'RH', v_payroll_run_jan_completed, now(), now()),
    ('00150004-0000-0000-0000-000000000000', v_bl_saude, 202501, 'LIQUIDATION', 606000.00, 'RH', v_payroll_run_jan_completed, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- LOTES DE PAGAMENTO (Payment Batch)
    -- ========================================================================
    INSERT INTO payment_batch (
        id, period_id, ministry_id, status, created_at, updated_at, created_by
    ) VALUES
    ('00160001-0000-0000-0000-000000000000', 202501, v_min_financas, 'CREATED', now(), now(), v_user_admin),
    ('00160002-0000-0000-0000-000000000000', 202502, v_min_financas, 'SENT_TO_BANK', now(), now(), v_user_admin)
    ON CONFLICT (id) DO NOTHING;
    
    SELECT id INTO v_batch_jan FROM payment_batch WHERE id = '00160001-0000-0000-0000-000000000000';
    SELECT id INTO v_batch_fev FROM payment_batch WHERE id = '00160002-0000-0000-0000-000000000000';
    
    -- ========================================================================
    -- ORDENS DE PAGAMENTO (Payment Order)
    -- Geradas a partir da folha de Janeiro
    -- ========================================================================
    -- Amilcar: Bruto = 604.000, Líquido = 604.000 - 42.280 - 1.812 - 46.172 = 513.736
    -- NOTA: payroll_run_id é bigint no schema mas UUID na entidade Java - usando NULL por enquanto
    INSERT INTO payment_order (
        id, payment_batch_id, payroll_run_id, agent_id, bank_account_id, budget_line_id,
        gross_amount, net_amount, status, created_at, updated_at
    ) VALUES
    ('00170001-0000-0000-0000-000000000000', v_batch_jan, NULL, v_agent_amilcar, v_account_amilcar, v_bl_financas,
     604000.00, 513736.00, 'CREATED', now(), now()),
    -- Francisca: Bruto = 552.000, Líquido = 552.000 - 38.640 - 1.656 - 41.336 = 470.368
    ('00170002-0000-0000-0000-000000000000', v_batch_jan, NULL, v_agent_francisca, v_account_francisca, v_bl_financas,
     552000.00, 470368.00, 'CREATED', now(), now()),
    -- João: Bruto = 606.000, Líquido = 606.000 - 42.420 - 1.818 - 46.178 = 515.584
    ('00170003-0000-0000-0000-000000000000', v_batch_jan, NULL, v_agent_joao, v_account_joao, v_bl_saude,
     606000.00, 515584.00, 'SENT_TO_BANK', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- CONFIRMAÇÕES DE PAGAMENTO DO TESOURO (Treasury Payment)
    -- ========================================================================
    INSERT INTO treasury_payment (
        id, payment_order_id, paid_at, transaction_ref, status, message, created_at, updated_at
    ) VALUES
    -- Amilcar - Pago
    ('00180001-0000-0000-0000-000000000000', '00170001-0000-0000-0000-000000000000', '2025-01-15 10:30:00', 'TXN-2025-001-001', 'PAID', 'Pagamento confirmado pelo banco', now(), now()),
    -- Francisca - Pendente
    ('00180002-0000-0000-0000-000000000000', '00170002-0000-0000-0000-000000000000', NULL, NULL, 'PENDING', NULL, now(), now()),
    -- João - Pago
    ('00180003-0000-0000-0000-000000000000', '00170003-0000-0000-0000-000000000000', '2025-01-15 11:15:00', 'TXN-2025-001-003', 'PAID', 'Pagamento confirmado pelo banco', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- EXECUÇÕES ORÇAMENTÁRIAS - PAYMENT (após confirmação do tesouro)
    -- ========================================================================
    INSERT INTO budget_execution (
        id, budget_line_id, period_id, movement_type, amount, source_module, reference_id, created_at, updated_at
    ) VALUES
    -- Pagamentos confirmados
    ('00150005-0000-0000-0000-000000000000', v_bl_financas, 202501, 'PAYMENT', 513736.00, 'TREASURY', '00170001-0000-0000-0000-000000000000', now(), now()),
    ('00150006-0000-0000-0000-000000000000', v_bl_saude, 202501, 'PAYMENT', 515584.00, 'TREASURY', '00170003-0000-0000-0000-000000000000', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- ITENS DE FOLHA PARA FEVEREIRO (para testar múltiplos períodos)
    -- ========================================================================
    INSERT INTO payroll_item (
        id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
        description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
    ) VALUES
    -- Amilcar - Fevereiro
    ('00140010-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'EARNING', v_earning_vencimento, NULL,
     'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_financas, now(), now()),
    ('00140011-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'EARNING', v_earning_abono, NULL,
     'Abono de Família (2 dep.)', 2000.00, 2.00, 4000.00, v_bl_financas, now(), now()),
    ('00140012-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_inps,
     'INPS 7%', 42280.00, 1.00, 42280.00, NULL, now(), now()),
    ('00140013-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_selo,
     'Imposto de Selo 0.3%', 1812.00, 1.00, 1812.00, NULL, now(), now()),
    ('00140014-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_irps,
     'IRPS', 46172.00, 1.00, 46172.00, NULL, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    RAISE NOTICE '=== DADOS PARA TESTES FUNCIONAIS INSERIDOS COM SUCESSO ===';
    RAISE NOTICE 'Períodos de folha adicionados: 2';
    RAISE NOTICE 'Execuções de folha criadas: 3';
    RAISE NOTICE 'Itens de folha completos: 15+';
    RAISE NOTICE 'Execuções orçamentárias: 6';
    RAISE NOTICE 'Lotes de pagamento: 2';
    RAISE NOTICE 'Ordens de pagamento: 3';
    RAISE NOTICE 'Confirmações de pagamento: 3';
    
END $$;

-- ========================================================================
-- VERIFICAÇÃO FINAL DOS DADOS INSERIDOS
-- ========================================================================
SELECT 'PERIODOS FOLHA' as tipo, COUNT(*)::text as total FROM payroll_period WHERE fiscal_year = 2025
UNION ALL
SELECT 'EXECUCOES FOLHA', COUNT(*)::text FROM payroll_run WHERE period_id IN (
    SELECT id FROM payroll_period WHERE fiscal_year = 2025
)
UNION ALL
SELECT 'ITENS FOLHA', COUNT(*)::text FROM payroll_item WHERE payroll_run_id IN (
    SELECT id FROM payroll_run WHERE period_id IN (
        SELECT id FROM payroll_period WHERE fiscal_year = 2025
    )
)
UNION ALL
SELECT 'EXECUCOES ORCAMENTARIAS', COUNT(*)::text FROM budget_execution WHERE period_id >= 202501
UNION ALL
SELECT 'LOTES PAGAMENTO', COUNT(*)::text FROM payment_batch WHERE period_id >= 202501
UNION ALL
SELECT 'ORDENS PAGAMENTO', COUNT(*)::text FROM payment_order WHERE payment_batch_id IN (
    SELECT id FROM payment_batch WHERE period_id >= 202501
)
UNION ALL
SELECT 'CONFIRMACOES TESOURO', COUNT(*)::text FROM treasury_payment WHERE payment_order_id IN (
    SELECT id FROM payment_order WHERE payment_batch_id IN (
        SELECT id FROM payment_batch WHERE period_id >= 202501
    )
)
ORDER BY tipo;

