-- ============================================
-- SCRIPT COMPLETO DE DADOS DE TESTE - SIGEFP
-- Baseado no mapeamento completo de entidades
-- ============================================

-- IMPORTANTE: Este script usa os dados existentes do usuario e adiciona dados complementares

DO $$
DECLARE
    -- IDs existentes (do usuario)
    v_min_existente UUID;
    v_ou_sec UUID;
    v_ou_dir UUID;
    
    -- IDs novos
    v_min_saude UUID;
    v_min_educacao UUID;
    v_ou_tesouro UUID;
    v_ou_orcamento UUID;
    v_ou_hospital UUID;
    v_ou_escola UUID;
    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;
    
    -- Ano Fiscal
    v_fy_2025 UUID;
BEGIN
    -- ============================================
    -- 1. OBTER DADOS EXISTENTES
    -- ============================================
    SELECT id INTO v_min_existente FROM ministry WHERE code = 'MIN-001';
    SELECT id INTO v_ou_sec FROM org_unit WHERE code = 'SEC-001';
    SELECT id INTO v_ou_dir FROM org_unit WHERE code = 'DIR-003';
    
    RAISE NOTICE 'Ministerio existente: %', v_min_existente;
    
    -- ============================================
    -- 2. INSERIR MINISTERIOS ADICIONAIS
    -- ============================================
    INSERT INTO ministry (id, code, name, is_active, created_at, updated_at)
    VALUES 
        ('22222222-2222-2222-2222-222222222222', 'MIN-002', 'Ministerio da Saude Publica', true, now(), now()),
        ('33333333-3333-3333-3333-333333333333', 'MIN-003', 'Ministerio da Educacao Nacional', 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';
    
    -- ============================================
    -- 3. INSERIR UNIDADES ORGANICAS
    -- IMPORTANTE: unit_type e OBRIGATORIO!
    -- ============================================
    INSERT INTO org_unit (id, code, name, ministry_id, parent_unit_id, unit_type, is_active, created_at, updated_at)
    VALUES 
        ('44444444-4444-4444-4444-444444444444', 'UO-001', 'Direcao-Geral do Tesouro', v_min_existente, NULL, 'DIRECTORATE', true, now(), now()),
        ('55555555-5555-5555-5555-555555555555', 'UO-002', 'Direcao-Geral do Orcamento', v_min_existente, NULL, 'DIRECTORATE', true, now(), now()),
        ('66666666-6666-6666-6666-666666666666', 'UO-003', 'Hospital Nacional Simao Mendes', v_min_saude, NULL, 'HOSPITAL', true, now(), now()),
        ('77777777-7777-7777-7777-777777777777', 'UO-004', 'Escola Secundaria de Bissau', v_min_educacao, NULL, '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';
    
    -- ============================================
    -- 4. INSERIR CARGOS (POSITIONS)
    -- IMPORTANTE: org_unit_id e OBRIGATORIO!
    -- ============================================
    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';
    
    -- ============================================
    -- 5. 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;
    
    -- Adicionar escaloes 2 e 3
    INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at)
    VALUES 
        ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', v_grade_a, 2, now(), now()),
        ('ffffffff-ffff-ffff-ffff-ffffffffffff', v_grade_a, 3, now(), now())
    ON CONFLICT (grade_id, step_number) DO NOTHING;
    
    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;
    
    -- Valores da grelha salarial
    INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at)
    VALUES 
        ('10101010-1010-1010-1010-101010101010', v_step_2, 550000.00, '2024-01-01', now(), now()),
        ('20202020-2020-2020-2020-202020202020', v_step_3, 600000.00, '2024-01-01', now(), now())
    ON CONFLICT DO NOTHING;
    
    -- ============================================
    -- 6. ANO FISCAL
    -- ============================================
    SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
    
    -- ============================================
    -- 7. AGENTES (usando UUIDs simples, nao FKs)
    -- ============================================
    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;
    
    -- ============================================
    -- 8. LINHAS ORCAMENTAIS
    -- ============================================
    INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
    VALUES 
        ('f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1f1', v_fy_2025, '2025-MINFIN-311100', 'Vencimentos Base - Financas', v_min_existente, v_ou_tesouro, '311100', now(), now()),
        ('f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2f2', v_fy_2025, '2025-MINSAUDE-311100', 'Vencimentos Base - Saude', v_min_saude, v_ou_hospital, '311100', now(), now()),
        ('f3f3f3f3-f3f3-f3f3-f3f3-f3f3f3f3f3f3', v_fy_2025, '2025-MINEDU-311100', 'Vencimentos Base - Educacao', v_min_educacao, v_ou_escola, '311100', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    RAISE NOTICE '=== DADOS DE TESTE INSERIDOS COM SUCESSO ===';
    RAISE NOTICE 'Ministerios adicionados: 2';
    RAISE NOTICE 'Unidades Organicas adicionadas: 4';
    RAISE NOTICE 'Cargos adicionados: 4';
    RAISE NOTICE 'Agentes adicionados: 5';
    RAISE NOTICE 'Linhas Orcamentais adicionadas: 3';
END $$;

-- Verificar resultados finais
SELECT 'MINISTERIOS' as tipo, 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 'AGENTES', COUNT(*)::text FROM agents
UNION ALL
SELECT 'LINHAS ORCAMENTAIS', COUNT(*)::text FROM budget_line;
