-- ============================================================================
-- TEST: Validar FK Constraints - EPIC-001 FK Débiles
-- Verifica que los FK constraints condicionales fueron creados correctamente
-- ============================================================================
-- Uso:
--   PGPASSWORD=erp_dev_2026 psql -h localhost -U erp_admin -d erp_construccion_db -f validate-fk-constraints.sql
-- ============================================================================

\echo '============================================'
\echo 'TEST: Validación de FK Constraints'
\echo '============================================'
\echo ''

-- Crear tabla temporal para resultados
DROP TABLE IF EXISTS _fk_test_results;
CREATE TEMP TABLE _fk_test_results (
    id SERIAL PRIMARY KEY,
    test_name VARCHAR(100),
    expected_constraint VARCHAR(100),
    status VARCHAR(20),
    details TEXT
);

-- ============================================================================
-- INVENTORY SCHEMA - FK Constraints
-- ============================================================================
\echo 'Verificando schema INVENTORY...'

-- Test 1: fk_almacenes_proyecto_warehouse
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Almacenes Proyecto → Warehouses',
    'fk_almacenes_proyecto_warehouse',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_almacenes_proyecto_warehouse')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'inventory' AND tablename = 'warehouses')
         THEN 'Tabla warehouses existe - FK esperado'
         ELSE 'Tabla warehouses NO existe - FK no aplicable'
    END;

-- Test 2: fk_requisicion_lineas_product
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Requisicion Lineas → Products',
    'fk_requisicion_lineas_product',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_requisicion_lineas_product')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'products' AND tablename = 'products')
         THEN 'Tabla products existe - FK esperado'
         ELSE 'Tabla products NO existe - FK no aplicable'
    END;

-- Test 3: fk_requisicion_lineas_unit
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Requisicion Lineas → UOM',
    'fk_requisicion_lineas_unit',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_requisicion_lineas_unit')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'uom')
         THEN 'Tabla uom existe - FK esperado'
         ELSE 'Tabla uom NO existe - FK no aplicable'
    END;

-- Test 4: fk_requisiciones_obra_dest_warehouse
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Requisiciones Obra → Dest Warehouse',
    'fk_requisiciones_obra_dest_warehouse',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_requisiciones_obra_dest_warehouse')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para destination_warehouse_id';

-- Test 5: fk_requisiciones_obra_purchase_order
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Requisiciones Obra → Purchase Orders',
    'fk_requisiciones_obra_purchase_order',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_requisiciones_obra_purchase_order')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'purchases' AND tablename = 'purchase_orders')
         THEN 'Tabla purchase_orders existe - FK esperado'
         ELSE 'Tabla purchase_orders NO existe - FK no aplicable'
    END;

-- Test 6: fk_consumos_obra_product
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Consumos Obra → Products',
    'fk_consumos_obra_product',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_consumos_obra_product')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para product_id en consumos';

-- Test 7: fk_consumos_obra_stock_move
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Consumos Obra → Stock Moves',
    'fk_consumos_obra_stock_move',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_consumos_obra_stock_move')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'inventory' AND tablename = 'stock_moves')
         THEN 'Tabla stock_moves existe - FK esperado'
         ELSE 'Tabla stock_moves NO existe - FK no aplicable'
    END;

-- ============================================================================
-- PURCHASE SCHEMA - FK Constraints
-- ============================================================================
\echo 'Verificando schema PURCHASE...'

-- Test 8: fk_po_construction_purchase_order
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'PO Construction → Purchase Orders',
    'fk_po_construction_purchase_order',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_po_construction_purchase_order')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'purchases' AND tablename = 'purchase_orders')
         THEN 'Tabla purchase_orders existe - FK esperado'
         ELSE 'Tabla purchase_orders NO existe - FK no aplicable'
    END;

-- Test 9: fk_supplier_construction_partner
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Supplier Construction → Partners',
    'fk_supplier_construction_partner',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_supplier_construction_partner')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'partners' AND tablename = 'partners')
         THEN 'Tabla partners existe - FK esperado'
         ELSE 'Tabla partners NO existe - FK no aplicable'
    END;

-- Test 10: fk_comparativo_winner_supplier
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Comparativo → Winner Supplier',
    'fk_comparativo_winner_supplier',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_comparativo_winner_supplier')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para winner_supplier_id';

-- Test 11: fk_comparativo_prov_supplier
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Comparativo Prov → Supplier',
    'fk_comparativo_prov_supplier',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_comparativo_prov_supplier')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para supplier_id en comparativo_proveedores';

-- Test 12: fk_comparativo_prod_product
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Comparativo Prod → Product',
    'fk_comparativo_prod_product',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_comparativo_prod_product')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para product_id en comparativo_productos';

-- ============================================================================
-- HSE SCHEMA - FK Constraints
-- ============================================================================
\echo 'Verificando schema HSE...'

-- Test 13: fk_epp_inventario_almacen
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'EPP Inventario → Almacen Temporal',
    'fk_epp_inventario_almacen',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_epp_inventario_almacen')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para almacen_id en epp_inventario';

-- Test 14: fk_epp_movimientos_almacen_origen
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'EPP Movimientos → Almacen Origen',
    'fk_epp_movimientos_almacen_origen',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_epp_movimientos_almacen_origen')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para almacen_origen_id';

-- Test 15: fk_epp_movimientos_almacen_destino
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'EPP Movimientos → Almacen Destino',
    'fk_epp_movimientos_almacen_destino',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_epp_movimientos_almacen_destino')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para almacen_destino_id';

-- ============================================================================
-- DOCUMENTS SCHEMA - FK Constraints
-- ============================================================================
\echo 'Verificando schema DOCUMENTS...'

-- Test 16: fk_documents_parent
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Documents → Parent Document',
    'fk_documents_parent',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_documents_parent')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para parent_document_id';

-- Test 17: fk_access_logs_document
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Access Logs → Document',
    'fk_access_logs_document',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_access_logs_document')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para document_id';

-- Test 18: fk_access_logs_user
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Access Logs → User',
    'fk_access_logs_user',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_access_logs_user')
         THEN 'PASS' ELSE 'FAIL' END,
    CASE WHEN EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'auth' AND tablename = 'users')
         THEN 'Tabla users existe - FK esperado'
         ELSE 'Tabla users NO existe - FK no aplicable'
    END;

-- Test 19: fk_document_shares_shared_by
INSERT INTO _fk_test_results (test_name, expected_constraint, status, details)
SELECT
    'Document Shares → Shared By',
    'fk_document_shares_shared_by',
    CASE WHEN EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_document_shares_shared_by')
         THEN 'PASS' ELSE 'FAIL' END,
    'FK para shared_by_id';

-- ============================================================================
-- RESULTADOS
-- ============================================================================
\echo ''
\echo '============================================'
\echo 'RESULTADOS DE TESTS FK CONSTRAINTS'
\echo '============================================'

SELECT
    id,
    test_name,
    status,
    details
FROM _fk_test_results
ORDER BY id;

\echo ''
\echo '============================================'
\echo 'RESUMEN'
\echo '============================================'

SELECT
    status,
    COUNT(*) as total,
    ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM _fk_test_results), 1) as porcentaje
FROM _fk_test_results
GROUP BY status
ORDER BY status;

\echo ''
\echo 'NOTA: Los tests con FAIL donde la tabla referenciada NO existe son esperados.'
\echo '      Los FK constraints son condicionales - solo se crean si la tabla destino existe.'
\echo ''

-- ============================================================================
-- INDICES ADICIONALES
-- ============================================================================
\echo '============================================'
\echo 'VERIFICACION DE INDICES ADICIONALES'
\echo '============================================'

SELECT
    indexname,
    CASE WHEN EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = t.indexname)
         THEN 'EXISTE' ELSE 'NO EXISTE' END as status
FROM (
    VALUES
        ('idx_comparativo_prod_product_id'),
        ('idx_epp_inventario_almacen_id'),
        ('idx_epp_movimientos_almacen_origen'),
        ('idx_epp_movimientos_almacen_destino'),
        ('idx_documents_parent'),
        ('idx_document_shares_shared_by')
) AS t(indexname);

\echo ''
\echo 'Test completado.'
