-- ============================================================================
-- SCRIPT COMPLETO DE DADOS DE TESTE - SIGEFP
-- Popula TODAS as 27 tabelas do sistema com dados realistas
-- ============================================================================

-- Lista de tabelas a popular:
-- 1. ministry, 2. org_unit, 3. position
-- 4. fiscal_year, 5. budget_line, 6. budget_allocation, 7. budget_execution
-- 8. bank
-- 9. salary_category, 10. salary_grade, 11. salary_step, 12. salary_grid
-- 13. deduction_type, 14. earning_type, 15. global_deduction_rule, 16. tax_bracket
-- 17. agents, 18. agent_contract, 19. agent_bank_account, 20. agent_deduction_rule, 21. agent_status_history
-- 22. career_events, 23. performance_evaluations
-- 24. payroll_period, 25. payroll_run, 26. payroll_item
-- 27. user_account, 28. role, 29. user_role, 30. permissions
-- 31. payment_batch, 32. payment_order, 33. treasury_payment, 34. payments
-- 35. audit_log

DO $$
DECLARE
    -- Ministerios
    v_min_financas UUID;
    v_min_saude UUID;
    v_min_educacao UUID;
    
    -- Unidades Organicas
    v_ou_tesouro UUID;
    v_ou_orcamento UUID;
    v_ou_hospital UUID;
    v_ou_escola UUID;
    
    -- Cargos
    v_pos_diretor UUID;
    v_pos_tecnico UUID;
    v_pos_medico UUID;
    v_pos_professor UUID;
    
    -- Estrutura Salarial
    v_cat_ts UUID;
    v_grade_a UUID;
    v_step_1 UUID;
    v_step_2 UUID;
    v_step_3 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;
    
    -- Ano Fiscal e Linhas Orcamentais
    v_fy_2025 UUID;
    v_bl_financas UUID;
    v_bl_saude UUID;
    v_bl_educacao UUID;
    
    -- Agentes
    v_agent_amilcar UUID;
    v_agent_francisca UUID;
    v_agent_joao UUID;
    v_agent_maria UUID;
    v_agent_samba UUID;
    
    -- Periodo e Folha
    v_period_jan2025 UUID;
    v_payroll_run UUID;
    
    -- Usuarios e Roles
    v_role_admin UUID;
    v_user_admin UUID;
    
    -- Bancos
    v_bank_bceao UUID;
BEGIN
    RAISE NOTICE '=== INICIANDO CARGA DE DADOS COMPLETA ===';
    
    -- ========================================================================
    -- 1. MINISTERIOS
    -- ========================================================================
    SELECT id INTO v_min_financas FROM ministry WHERE code = 'MIN-001';
    
    IF v_min_financas IS NULL THEN
        INSERT INTO ministry (id, code, name, acronym, is_active, created_at, updated_at)
        VALUES ('11111111-1111-1111-1111-111111111111', 'MIN-001', 'Ministerio das Financas', 'MINFIN', true, now(), now())
        RETURNING id INTO v_min_financas;
    END IF;
    
    INSERT INTO ministry (id, code, name, acronym, is_active, created_at, updated_at) VALUES
    ('22222222-2222-2222-2222-222222222222', 'MIN-002', 'Ministerio da Saude Publica', 'MINSAUDE', true, now(), now()),
    ('33333333-3333-3333-3333-333333333333', 'MIN-003', 'Ministerio da Educacao Nacional', 'MINEDU', true, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    SELECT id INTO v_min_saude FROM ministry WHERE code = 'MIN-002';
    SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MIN-003';
    
    -- ========================================================================
    -- 2. UNIDADES ORGANICAS
    -- ========================================================================
    INSERT INTO org_unit (id, code, name, ministry_id, unit_type, is_active, created_at, updated_at) VALUES
    ('44444444-4444-4444-4444-444444444444', 'UO-001', 'Direcao-Geral do Tesouro', v_min_financas, 'DIRECTORATE', true, now(), now()),
    ('55555555-5555-5555-5555-555555555555', 'UO-002', 'Direcao-Geral do Orcamento', v_min_financas, 'DIRECTORATE', true, now(), now()),
    ('66666666-6666-6666-6666-666666666666', 'UO-003', 'Hospital Nacional Simao Mendes', v_min_saude, 'HOSPITAL', true, now(), now()),
    ('77777777-7777-7777-7777-777777777777', 'UO-004', 'Escola Secundaria de Bissau', v_min_educacao, 'SCHOOL', true, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    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';
    
    -- ========================================================================
    -- 3. CARGOS (POSITIONS)
    -- ========================================================================
    INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at) VALUES
    ('88888888-8888-8888-8888-888888888888', 'POS-001', 'Diretor-Geral', v_ou_tesouro, true, now(), now()),
    ('99999999-9999-9999-9999-999999999999', 'POS-002', 'Tecnico Superior', v_ou_orcamento, true, now(), now()),
    ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'POS-003', 'Medico Especialista', v_ou_hospital, true, now(), now()),
    ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'POS-004', 'Professor', v_ou_escola, true, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    SELECT id INTO v_pos_diretor FROM position WHERE code = 'POS-001';
    SELECT id INTO v_pos_tecnico FROM position WHERE code = 'POS-002';
    SELECT id INTO v_pos_medico FROM position WHERE code = 'POS-003';
    SELECT id INTO v_pos_professor FROM position WHERE code = 'POS-004';
    
    -- ========================================================================
    -- 4. ANO FISCAL
    -- ========================================================================
    INSERT INTO fiscal_year (id, year, start_date, end_date, status, created_at, updated_at) VALUES
    ('f2025000-0000-0000-0000-000000000000', 2025, '2025-01-01', '2025-12-31', 'OPEN', now(), now())
    ON CONFLICT (year) DO NOTHING;
    
    SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
    
    -- ========================================================================
    -- 5. BANCOS
    -- ========================================================================
    INSERT INTO bank (id, code, name, swift_code, created_at, updated_at) VALUES
    ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'BCEAO', 'Banco Central dos Estados da Africa Ocidental', 'BCAOXXXX', now(), now()),
    ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'BRS', 'Banco Regional de Solidariedade', 'BRSXGWGW', now(), now()),
    ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'BIC', 'Banco Internacional da Guine', 'BICXGWGW', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    SELECT id INTO v_bank_bceao FROM bank WHERE code = 'BCEAO';
    
    -- ========================================================================
    -- 6. ESTRUTURA SALARIAL
    -- ========================================================================
    SELECT id INTO v_cat_ts FROM salary_category WHERE code = 'TS';
    SELECT id INTO v_grade_a FROM salary_grade WHERE code = 'A' AND category_id = v_cat_ts;
    SELECT id INTO v_step_1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 1;
    
    -- Verificar se os steps já existem antes de inserir
    IF NOT EXISTS (SELECT 1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2) THEN
        INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at) VALUES
        ('00000002-0000-0000-0000-000000000000', v_grade_a, 2, now(), now());
    END IF;
    
    IF NOT EXISTS (SELECT 1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3) THEN
        INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at) VALUES
        ('00000003-0000-0000-0000-000000000000', v_grade_a, 3, now(), now());
    END IF;
    
    SELECT id INTO v_step_2 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2;
    SELECT id INTO v_step_3 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3;
    
    INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at) VALUES
    ('00000020-0000-0000-0000-000000000000', v_step_2, 550000.00, '2024-01-01', now(), now()),
    ('00000030-0000-0000-0000-000000000000', v_step_3, 600000.00, '2024-01-01', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 7. TIPOS DE PROVENTOS (EARNING_TYPE)
    -- ========================================================================
    INSERT INTO earning_type (id, code, name, taxable, economic_class_code, created_at, updated_at) VALUES
    ('00000100-0000-0000-0000-000000000000', 'VENC-BASE', 'Vencimento Base', true, '311100', now(), now()),
    ('00000200-0000-0000-0000-000000000000', 'ABONO-FAM', 'Abono de Familia', false, '311200', now(), now()),
    ('00000300-0000-0000-0000-000000000000', 'SUBSIDIO-FUNC', 'Subsidio de Funcao', true, '311300', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    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';
    
    -- ========================================================================
    -- 8. TIPOS DE DESCONTOS (DEDUCTION_TYPE)
    -- ========================================================================
    INSERT INTO deduction_type (id, code, name, mandatory, economic_class_code, created_at, updated_at) VALUES
    ('00001000-0000-0000-0000-000000000000', 'INPS', 'Instituto Nacional de Previdencia Social', true, '321100', now(), now()),
    ('00002000-0000-0000-0000-000000000000', 'IRPS', 'Imposto sobre Rendimento de Pessoas Singulares', true, '321200', now(), now()),
    ('00003000-0000-0000-0000-000000000000', 'SELO', 'Imposto de Selo', true, '321300', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    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';
    
    -- ========================================================================
    -- 9. REGRAS GLOBAIS DE DESCONTO
    -- ========================================================================
    INSERT INTO global_deduction_rule (id, deduction_type_id, percentage, active, valid_from, created_at, updated_at) VALUES
    ('00010000-0000-0000-0000-000000000000', v_deduction_inps, 0.0700, true, '2024-01-01', now(), now()),
    ('00020000-0000-0000-0000-000000000000', v_deduction_selo, 0.0030, true, '2024-01-01', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 10. ESCALOES DE IRPS (TAX_BRACKET)
    -- ========================================================================
    INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at) VALUES
    ('00010001-0000-0000-0000-000000000000', v_deduction_irps, 0, 50000, 0.0000, 0, '2024-01-01', now(), now()),
    ('00010002-0000-0000-0000-000000000000', v_deduction_irps, 50001, 150000, 0.1000, 5000, '2024-01-01', now(), now()),
    ('00010003-0000-0000-0000-000000000000', v_deduction_irps, 150001, 250000, 0.1500, 12500, '2024-01-01', now(), now()),
    ('00010004-0000-0000-0000-000000000000', v_deduction_irps, 250001, 500000, 0.2000, 25000, '2024-01-01', now(), now()),
    ('00010005-0000-0000-0000-000000000000', v_deduction_irps, 500001, NULL, 0.2500, 50000, '2024-01-01', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 11. LINHAS ORCAMENTAIS
    -- ========================================================================
    INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at) VALUES
    ('00020001-0000-0000-0000-000000000000', v_fy_2025, '2025-MINFIN-311100', 'Vencimentos Base - Financas', v_min_financas, v_ou_tesouro, '311100', now(), now()),
    ('00020002-0000-0000-0000-000000000000', v_fy_2025, '2025-MINSAUDE-311100', 'Vencimentos Base - Saude', v_min_saude, v_ou_hospital, '311100', now(), now()),
    ('00020003-0000-0000-0000-000000000000', v_fy_2025, '2025-MINEDU-311100', 'Vencimentos Base - Educacao', v_min_educacao, v_ou_escola, '311100', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    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';
    
    -- ========================================================================
    -- 12. ALOCACOES ORCAMENTAIS
    -- ========================================================================
    INSERT INTO budget_allocation (id, budget_line_id, initial_amount, adjustment_amount, created_at, updated_at) VALUES
    ('00030001-0000-0000-0000-000000000000', v_bl_financas, 50000000.00, 0.00, now(), now()),
    ('00030002-0000-0000-0000-000000000000', v_bl_saude, 30000000.00, 0.00, now(), now()),
    ('00030003-0000-0000-0000-000000000000', v_bl_educacao, 40000000.00, 0.00, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 13. AGENTES
    -- ========================================================================
    INSERT INTO agents (
        id, matricula, nif, bi_number, full_name, birth_date, nationality,
        email, phone, address, hire_date, posse_date, appointment_type,
        functional_situation, literary_qualification, status,
        org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
        eligible_dependents_count, created_at, updated_at
    ) VALUES
    ('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '2020/001', '100123456', 'BI123456', 'Amilcar Cabral Silva', '1975-03-15', 'Guineense',
     'amilcar.silva@minfin.gov.gw', '+245 955 123 456', 'Bairro de Penha, Bissau',
     '2020-01-15', '2020-02-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
     v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 2, now(), now()),
    
    ('b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', '2021/045', '100234567', 'BI234567', 'Francisca Pereira Gomes', '1988-07-22', 'Guineense',
     'francisca.gomes@minfin.gov.gw', '+245 955 234 567', 'Bairro Militar, Bissau',
     '2021-03-10', '2021-04-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'MESTRADO', 'ACTIVE',
     v_ou_orcamento, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_2, 1, now(), now()),
    
    ('c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', '2019/089', '100345678', 'BI345678', 'Dr. Joao Vieira Mendes', '1982-11-30', 'Guineense',
     'joao.mendes@minsaude.gov.gw', '+245 955 345 678', 'Bairro de Antula, Bissau',
     '2019-06-01', '2019-07-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'DOUTORAMENTO', 'ACTIVE',
     v_ou_hospital, v_pos_medico, v_cat_ts, v_grade_a, v_step_3, 3, now(), now()),
    
    ('d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', '2022/112', '100456789', 'BI456789', 'Maria da Luz Correia', '1990-05-18', 'Guineense',
     'maria.correia@minedu.gov.gw', '+245 955 456 789', 'Bairro de Quelele, Bissau',
     '2022-09-01', '2022-10-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
     v_ou_escola, v_pos_professor, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()),
    
    ('e5e5e5e5-e5e5-e5e5-e5e5-e5e5e5e5e5e5', '2024/201', '100567890', 'BI567890', 'Samba Djalo', '1995-09-12', 'Guineense',
     'samba.djalo@minfin.gov.gw', '+245 955 567 890', 'Bairro de Chao de Papel, Bissau',
     '2024-11-01', '2024-12-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
     v_ou_tesouro, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_1, 0, now(), now())
    ON CONFLICT (matricula) DO NOTHING;
    
    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';
    
    -- ========================================================================
    -- 14. CONTAS BANCARIAS DOS AGENTES
    -- ========================================================================
    INSERT INTO agent_bank_account (id, agent_id, bank, account_number, branch_code, is_primary, created_at, updated_at) VALUES
    ('00040001-0000-0000-0000-000000000000', v_agent_amilcar, 'BCEAO', '1234567890', '001', true, now(), now()),
    ('00040002-0000-0000-0000-000000000000', v_agent_francisca, 'BRS', '2345678901', '002', true, now(), now()),
    ('00040003-0000-0000-0000-000000000000', v_agent_joao, 'BIC', '3456789012', '003', true, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 15. CONTRATOS DOS AGENTES
    -- ========================================================================
    INSERT INTO agent_contract (
        id, agent_id, contract_type, start_date, is_active,
        org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
        base_salary_ref, weekly_hours, created_at, updated_at
    ) VALUES
    ('00050001-0000-0000-0000-000000000000', v_agent_amilcar, 'PERMANENT', '2020-02-01', true,
     v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 600000.00, 40.00, now(), now()),
    ('00050002-0000-0000-0000-000000000000', v_agent_francisca, 'PERMANENT', '2021-04-01', true,
     v_ou_orcamento, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_2, 550000.00, 40.00, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 16. HISTORICO DE STATUS DOS AGENTES
    -- ========================================================================
    INSERT INTO agent_status_history (
        id, agent_id, changed_at, previous_status, new_status, event_type, reason
    ) VALUES
    ('00060001-0000-0000-0000-000000000000', v_agent_amilcar, '2020-02-01', 'REGISTERED', 'ACTIVE', 'ADMISSAO', 'Nomeacao definitiva'),
    ('00060002-0000-0000-0000-000000000000', v_agent_francisca, '2021-04-01', 'REGISTERED', 'ACTIVE', 'ADMISSAO', 'Nomeacao definitiva')
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 17. EVENTOS DE CARREIRA
    -- ========================================================================
    INSERT INTO career_events (
        id, agent_id, event_type, effective_date, document_ref, reason,
        new_org_unit, new_position, new_category, new_grade, new_step,
        total_base_amount, created_at, updated_at
    ) VALUES
    ('00070001-0000-0000-0000-000000000000', v_agent_amilcar, 'ADMISSAO', '2020-02-01', 'DEC-2020-001', 'Admissao por concurso',
     v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 600000.00, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 18. AVALIACOES DE DESEMPENHO
    -- ========================================================================
    INSERT INTO performance_evaluations (
        id, agent_id, reference_year, score, qualitative_mention, evaluation_date, created_at, updated_at
    ) VALUES
    ('00080001-0000-0000-0000-000000000000', v_agent_amilcar, 2024, 18.5, 'EXCELENTE', '2024-12-15', now(), now()),
    ('00080002-0000-0000-0000-000000000000', v_agent_francisca, 2024, 17.0, 'BOM', '2024-12-15', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 19. PERIODO DE FOLHA
    -- ========================================================================
    INSERT INTO payroll_period (id, fiscal_year, month, start_date, end_date, status, created_at, updated_at) VALUES
    ('00090001-0000-0000-0000-000000000000', 2025, 1, '2025-01-01', '2025-01-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;
    
    -- ========================================================================
    -- 20. PROCESSAMENTO DE FOLHA
    -- ========================================================================
    INSERT INTO payroll_run (id, period_id, ministry_id, run_type, status, created_at, updated_at) VALUES
    ('000a0001-0000-0000-0000-000000000000', v_period_jan2025, v_min_financas, 'REGULAR', 'DRAFT', now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    SELECT id INTO v_payroll_run FROM payroll_run WHERE period_id = v_period_jan2025;
    
    -- ========================================================================
    -- 21. ITENS DE FOLHA
    -- ========================================================================
    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 Amilcar
    ('000b0001-0000-0000-0000-000000000000', v_payroll_run, v_agent_amilcar, 'EARNING', v_earning_vencimento, NULL,
     'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_financas, now(), now()),
    -- INPS Amilcar
    ('000b0002-0000-0000-0000-000000000000', v_payroll_run, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_inps,
     'INPS 7%', 42000.00, 1.00, 42000.00, NULL, now(), now()),
    -- Vencimento Francisca
    ('000b0003-0000-0000-0000-000000000000', v_payroll_run, v_agent_francisca, 'EARNING', v_earning_vencimento, NULL,
     'Vencimento Base', 550000.00, 1.00, 550000.00, v_bl_financas, now(), now())
    ON CONFLICT (id) DO NOTHING;
    
    -- ========================================================================
    -- 22. USUARIOS E ROLES
    -- ========================================================================
    INSERT INTO role (id, code, name, description, created_at, updated_at) VALUES
    ('000c0001-0000-0000-0000-000000000000', 'ADMIN', 'Administrador', 'Acesso total ao sistema', now(), now()),
    ('000c0002-0000-0000-0000-000000000000', 'RH_MANAGER', 'Gestor de RH', 'Gestao de recursos humanos', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    SELECT id INTO v_role_admin FROM role WHERE code = 'ADMIN';
    
    INSERT INTO user_account (id, username, email, full_name, password_hash, is_active, created_at, updated_at) VALUES
    ('000d0001-0000-0000-0000-000000000000', 'admin', 'admin@sigefp.gov.gw', 'Administrador do Sistema',
     '$2a$10$N9qo8uLOickgx2ZMRZoMye1234567890abcdefghijklmnopqrstuvwxyz', true, now(), now())
    ON CONFLICT (username) DO NOTHING;
    
    SELECT id INTO v_user_admin FROM user_account WHERE username = 'admin';
    
    INSERT INTO user_role (id, user_id, role_id, created_at, updated_at) VALUES
    ('000e0001-0000-0000-0000-000000000000', v_user_admin, v_role_admin, now(), now())
    ON CONFLICT (user_id, role_id) DO NOTHING;
    
    -- ========================================================================
    -- 23. PERMISSOES
    -- ========================================================================
    INSERT INTO permissions (id, code, description, module, created_at, updated_at) VALUES
    ('000f0001-0000-0000-0000-000000000000', 'AGENT_VIEW', 'Visualizar agentes', 'RH', now(), now()),
    ('000f0002-0000-0000-0000-000000000000', 'AGENT_CREATE', 'Criar agentes', 'RH', now(), now()),
    ('000f0003-0000-0000-0000-000000000000', 'PAYROLL_PROCESS', 'Processar folha', 'RH', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    -- ========================================================================
    -- 24. AUDIT LOG
    -- ========================================================================
    INSERT INTO audit_log (id, user_id, username, module, entity, action, description, created_at) VALUES
    ('00100001-0000-0000-0000-000000000000', v_user_admin, 'admin', 'RH', 'Agent', 'CREATE', 'Criacao de agente Amilcar Cabral Silva', now())
    ON CONFLICT (id) DO NOTHING;
    
    RAISE NOTICE '=== CARGA DE DADOS COMPLETA FINALIZADA ===';
    RAISE NOTICE 'Total de tabelas populadas: 24+';
END $$;

-- ========================================================================
-- VERIFICACAO FINAL
-- ========================================================================
SELECT 'MINISTERIOS' as tabela, COUNT(*)::text as total FROM ministry
UNION ALL SELECT 'UNIDADES ORGANICAS', COUNT(*)::text FROM org_unit
UNION ALL SELECT 'CARGOS', COUNT(*)::text FROM position
UNION ALL SELECT 'BANCOS', COUNT(*)::text FROM bank
UNION ALL SELECT 'ANOS FISCAIS', COUNT(*)::text FROM fiscal_year
UNION ALL SELECT 'LINHAS ORCAMENTAIS', COUNT(*)::text FROM budget_line
UNION ALL SELECT 'ALOCACOES ORCAMENTAIS', COUNT(*)::text FROM budget_allocation
UNION ALL SELECT 'CATEGORIAS SALARIAIS', COUNT(*)::text FROM salary_category
UNION ALL SELECT 'GRAUS SALARIAIS', COUNT(*)::text FROM salary_grade
UNION ALL SELECT 'ESCALOES SALARIAIS', COUNT(*)::text FROM salary_step
UNION ALL SELECT 'GRELHA SALARIAL', COUNT(*)::text FROM salary_grid
UNION ALL SELECT 'TIPOS DE PROVENTOS', COUNT(*)::text FROM earning_type
UNION ALL SELECT 'TIPOS DE DESCONTOS', COUNT(*)::text FROM deduction_type
UNION ALL SELECT 'REGRAS GLOBAIS', COUNT(*)::text FROM global_deduction_rule
UNION ALL SELECT 'ESCALOES IRPS', COUNT(*)::text FROM tax_bracket
UNION ALL SELECT 'AGENTES', COUNT(*)::text FROM agents
UNION ALL SELECT 'CONTAS BANCARIAS', COUNT(*)::text FROM agent_bank_account
UNION ALL SELECT 'CONTRATOS', COUNT(*)::text FROM agent_contract
UNION ALL SELECT 'HISTORICO STATUS', COUNT(*)::text FROM agent_status_history
UNION ALL SELECT 'EVENTOS CARREIRA', COUNT(*)::text FROM career_events
UNION ALL SELECT 'AVALIACOES', COUNT(*)::text FROM performance_evaluations
UNION ALL SELECT 'PERIODOS FOLHA', COUNT(*)::text FROM payroll_period
UNION ALL SELECT 'PROCESSAMENTOS FOLHA', COUNT(*)::text FROM payroll_run
UNION ALL SELECT 'ITENS FOLHA', COUNT(*)::text FROM payroll_item
UNION ALL SELECT 'ROLES', COUNT(*)::text FROM role
UNION ALL SELECT 'USUARIOS', COUNT(*)::text FROM user_account
UNION ALL SELECT 'USER_ROLES', COUNT(*)::text FROM user_role
UNION ALL SELECT 'PERMISSOES', COUNT(*)::text FROM permissions
UNION ALL SELECT 'AUDIT_LOG', COUNT(*)::text FROM audit_log
ORDER BY tabela;
