-- Script Complementar de Dados de Teste
-- Usa o ministerio existente e adiciona dados adicionais

DO $$
DECLARE
    v_min_financas UUID;
    v_min_saude UUID;
    v_min_educacao UUID;
    v_cat_ts UUID;
    v_grade_a UUID;
    v_step_1 UUID;
    v_fy_2025 UUID;
BEGIN
    -- Obter ministerio existente
    SELECT id INTO v_min_financas FROM ministry WHERE code = 'MIN-001';
    
    -- Inserir ministerios adicionais (se nao existirem)
    INSERT INTO ministry (id, code, name, created_at, updated_at)
    VALUES ('22222222-2222-2222-2222-222222222222', 'MINSAUDE', 'Ministerio da Saude Publica', now(), now())
    ON CONFLICT (code) DO NOTHING
    RETURNING id INTO v_min_saude;
    
    IF v_min_saude IS NULL THEN
        SELECT id INTO v_min_saude FROM ministry WHERE code = 'MINSAUDE';
    END IF;
    
    INSERT INTO ministry (id, code, name, created_at, updated_at)
    VALUES ('33333333-3333-3333-3333-333333333333', 'MINEDU', 'Ministerio da Educacao Nacional', now(), now())
    ON CONFLICT (code) DO NOTHING
    RETURNING id INTO v_min_educacao;
    
    IF v_min_educacao IS NULL THEN
        SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MINEDU';
    END IF;
    
    -- Inserir Unidades Organicas
    INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
    VALUES ('44444444-4444-4444-4444-444444444444', 'DGT', 'Direcao-Geral do Tesouro', v_min_financas, NULL, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
    VALUES ('55555555-5555-5555-5555-555555555555', 'DGO', 'Direcao-Geral do Orcamento', v_min_financas, NULL, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
    VALUES ('66666666-6666-6666-6666-666666666666', 'HOSP-CENTRAL', 'Hospital Nacional Simao Mendes', v_min_saude, NULL, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
    VALUES ('77777777-7777-7777-7777-777777777777', 'ESC-SEC-BISSAU', 'Escola Secundaria de Bissau', v_min_educacao, NULL, now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    -- Inserir Cargos
    INSERT INTO position (id, code, title, description, created_at, updated_at)
    VALUES ('88888888-8888-8888-8888-888888888888', 'DIR-GERAL', 'Diretor-Geral', 'Cargo de direcao superior', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO position (id, code, title, description, created_at, updated_at)
    VALUES ('99999999-9999-9999-9999-999999999999', 'TEC-SUP', 'Tecnico Superior', 'Tecnico de nivel superior', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO position (id, code, title, description, created_at, updated_at)
    VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'MEDICO', 'Medico Especialista', 'Medico com especializacao', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO position (id, code, title, description, created_at, updated_at)
    VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'PROF', 'Professor do Ensino Secundario', 'Professor licenciado', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    -- Inserir 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())
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO bank (id, code, name, swift_code, created_at, updated_at)
    VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'BRS', 'Banco Regional de Solidariedade', 'BRSXGWGW', now(), now())
    ON CONFLICT (code) DO NOTHING;
    
    -- Obter estrutura salarial existente
    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;
    SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
    
    -- Adicionar escaloes (se nao existirem)
    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())
    ON CONFLICT (grade_id, step_number) DO NOTHING;
    
    INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at)
    VALUES ('ffffffff-ffff-ffff-ffff-ffffffffffff', v_grade_a, 3, now(), now())
    ON CONFLICT (grade_id, step_number) DO NOTHING;
    
    -- Valores da grelha
    INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at)
    SELECT '10101010-1010-1010-1010-101010101010', id, 550000.00, '2024-01-01', now(), now()
    FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2
    ON CONFLICT DO NOTHING;
    
    INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at)
    SELECT '20202020-2020-2020-2020-202020202020', id, 600000.00, '2024-01-01', now(), now()
    FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3
    ON CONFLICT DO NOTHING;
    
    -- Inserir Agentes (se nao existirem)
    INSERT INTO agents (
        id, matricula, nif, full_name, birth_date, nationality, bi_number,
        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
    )
    SELECT 
        'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '2020/001', '100123456', 'Amilcar Cabral Silva', '1975-03-15', 'Guineense', 'BI123456',
        'amilcar.silva@minfin.gov.gw', '+245 955 123 456', 'Bairro de Penha, Bissau',
        '2020-01-15', '2020-02-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
        ou.id, p.id, v_cat_ts, v_grade_a, ss.id, 2, now(), now()
    FROM org_unit ou, position p, salary_step ss
    WHERE ou.code = 'DGT' AND p.code = 'DIR-GERAL' AND ss.grade_id = v_grade_a AND ss.step_number = 3
    ON CONFLICT (matricula) DO NOTHING;
    
    INSERT INTO agents (
        id, matricula, nif, full_name, birth_date, nationality, bi_number,
        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
    )
    SELECT 
        'b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', '2021/045', '100234567', 'Francisca Pereira Gomes', '1988-07-22', 'Guineense', 'BI234567',
        'francisca.gomes@minfin.gov.gw', '+245 955 234 567', 'Bairro Militar, Bissau',
        '2021-03-10', '2021-04-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'MESTRADO', 'ACTIVE',
        ou.id, p.id, v_cat_ts, v_grade_a, ss.id, 1, now(), now()
    FROM org_unit ou, position p, salary_step ss
    WHERE ou.code = 'DGO' AND p.code = 'TEC-SUP' AND ss.grade_id = v_grade_a AND ss.step_number = 2
    ON CONFLICT (matricula) DO NOTHING;
    
    INSERT INTO agents (
        id, matricula, nif, full_name, birth_date, nationality, bi_number,
        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
    )
    SELECT 
        'c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', '2019/089', '100345678', 'Dr. Joao Vieira Mendes', '1982-11-30', 'Guineense', 'BI345678',
        'joao.mendes@minsaude.gov.gw', '+245 955 345 678', 'Bairro de Antula, Bissau',
        '2019-06-01', '2019-07-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'DOUTORAMENTO', 'ACTIVE',
        ou.id, p.id, v_cat_ts, v_grade_a, ss.id, 3, now(), now()
    FROM org_unit ou, position p, salary_step ss
    WHERE ou.code = 'HOSP-CENTRAL' AND p.code = 'MEDICO' AND ss.grade_id = v_grade_a AND ss.step_number = 3
    ON CONFLICT (matricula) DO NOTHING;
    
    INSERT INTO agents (
        id, matricula, nif, full_name, birth_date, nationality, bi_number,
        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
    )
    SELECT 
        'd4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', '2022/112', '100456789', 'Maria da Luz Correia', '1990-05-18', 'Guineense', 'BI456789',
        'maria.correia@minedu.gov.gw', '+245 955 456 789', 'Bairro de Quelele, Bissau',
        '2022-09-01', '2022-10-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
        ou.id, p.id, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()
    FROM org_unit ou, position p
    WHERE ou.code = 'ESC-SEC-BISSAU' AND p.code = 'PROF'
    ON CONFLICT (matricula) DO NOTHING;
    
    INSERT INTO agents (
        id, matricula, nif, full_name, birth_date, nationality, bi_number,
        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
    )
    SELECT 
        'e5e5e5e5-e5e5-e5e5-e5e5-e5e5e5e5e5e5', '2024/201', '100567890', 'Samba Djalo', '1995-09-12', 'Guineense', 'BI567890',
        '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',
        ou.id, p.id, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()
    FROM org_unit ou, position p
    WHERE ou.code = 'DGT' AND p.code = 'TEC-SUP'
    ON CONFLICT (matricula) DO NOTHING;
    
    -- Linhas orcamentais
    INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
    SELECT 'f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1f1', v_fy_2025, '2025-MINFIN-311100', 'Vencimentos Base - Financas', 
           v_min_financas, ou.id, '311100', now(), now()
    FROM org_unit ou WHERE ou.code = 'DGT'
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
    SELECT 'f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2f2', v_fy_2025, '2025-MINSAUDE-311100', 'Vencimentos Base - Saude', 
           v_min_saude, ou.id, '311100', now(), now()
    FROM org_unit ou WHERE ou.code = 'HOSP-CENTRAL'
    ON CONFLICT (code) DO NOTHING;
    
    INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
    SELECT 'f3f3f3f3-f3f3-f3f3-f3f3-f3f3f3f3f3f3', v_fy_2025, '2025-MINEDU-311100', 'Vencimentos Base - Educacao', 
           v_min_educacao, ou.id, '311100', now(), now()
    FROM org_unit ou WHERE ou.code = 'ESC-SEC-BISSAU'
    ON CONFLICT (code) DO NOTHING;
    
    RAISE NOTICE '=== DADOS DE TESTE INSERIDOS/ATUALIZADOS COM SUCESSO ===';
    RAISE NOTICE 'Script executado usando ministerio existente MIN-001';
END $$;

-- Verificar resultados
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;
