#!/bin/bash
# =============================================================================
# DROP AND RECREATE DATABASE - ERP CONSTRUCCION
# =============================================================================
# Script de carga limpia segun DIRECTIVA-POLITICA-CARGA-LIMPIA.md
#
# Uso: ./drop-and-recreate-database.sh [DATABASE_URL]
# Ejemplo: ./drop-and-recreate-database.sh "postgresql://user:pass@localhost:5433/erp_construccion"
# =============================================================================

set -e

# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuracion
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DDL_DIR="$SCRIPT_DIR/ddl"
SCHEMAS_DIR="$SCRIPT_DIR/schemas"
INIT_SCRIPTS_DIR="$SCRIPT_DIR/init-scripts"

# Database URL (por defecto desarrollo local)
DATABASE_URL="${1:-${DATABASE_URL:-postgresql://postgres:postgres@localhost:5433/erp_construccion}}"

# Extraer parametros de conexion
DB_HOST=$(echo "$DATABASE_URL" | sed -E 's|.*@([^:]+):.*|\1|')
DB_PORT=$(echo "$DATABASE_URL" | sed -E 's|.*:([0-9]+)/.*|\1|')
DB_NAME=$(echo "$DATABASE_URL" | sed -E 's|.*/([^?]+).*|\1|')
DB_USER=$(echo "$DATABASE_URL" | sed -E 's|.*://([^:]+):.*|\1|')

echo -e "${BLUE}=============================================================================${NC}"
echo -e "${BLUE}   ERP CONSTRUCCION - Carga Limpia de Base de Datos${NC}"
echo -e "${BLUE}=============================================================================${NC}"
echo ""
echo -e "Host:     ${YELLOW}$DB_HOST:$DB_PORT${NC}"
echo -e "Database: ${YELLOW}$DB_NAME${NC}"
echo -e "Usuario:  ${YELLOW}$DB_USER${NC}"
echo ""

# =============================================================================
# PASO 1: Verificar conexion
# =============================================================================
echo -e "${YELLOW}[1/6] Verificando conexion a PostgreSQL...${NC}"
if ! psql "$DATABASE_URL" -c "SELECT 1" > /dev/null 2>&1; then
    echo -e "${RED}ERROR: No se puede conectar a PostgreSQL${NC}"
    echo -e "${YELLOW}Verificar que PostgreSQL esta corriendo y las credenciales son correctas${NC}"
    exit 1
fi
echo -e "${GREEN}OK - Conexion establecida${NC}"
echo ""

# =============================================================================
# PASO 2: DROP schemas existentes (carga limpia)
# =============================================================================
echo -e "${YELLOW}[2/6] Eliminando schemas existentes (carga limpia)...${NC}"

# Lista de schemas a eliminar (orden inverso de dependencias)
SCHEMAS_TO_DROP=(
    "hse"
    "infonavit_management"
    "safety_management"
    "quality_management"
    "construction_management"
    "inventory_management"
    "purchasing_management"
    "financial_management"
    "project_management"
    "auth_management"
    "core_shared"
)

for schema in "${SCHEMAS_TO_DROP[@]}"; do
    if psql "$DATABASE_URL" -t -c "SELECT 1 FROM pg_namespace WHERE nspname = '$schema'" 2>/dev/null | grep -q 1; then
        psql "$DATABASE_URL" -c "DROP SCHEMA IF EXISTS $schema CASCADE" > /dev/null 2>&1
        echo -e "  - Schema ${YELLOW}$schema${NC} eliminado"
    fi
done
echo -e "${GREEN}OK - Schemas eliminados${NC}"
echo ""

# =============================================================================
# PASO 3: Ejecutar DDL inicial
# =============================================================================
echo -e "${YELLOW}[3/6] Ejecutando DDL inicial (extensiones, schemas base)...${NC}"

if [ -f "$INIT_SCRIPTS_DIR/01-init-database.sql" ]; then
    psql "$DATABASE_URL" -f "$INIT_SCRIPTS_DIR/01-init-database.sql" > /dev/null 2>&1
    echo -e "${GREEN}OK - DDL inicial ejecutado${NC}"
elif [ -f "$DDL_DIR/00-init.sql" ]; then
    psql "$DATABASE_URL" -f "$DDL_DIR/00-init.sql" > /dev/null 2>&1
    echo -e "${GREEN}OK - DDL inicial ejecutado (00-init.sql)${NC}"
else
    echo -e "${RED}ERROR: No se encontro archivo de inicializacion${NC}"
    exit 1
fi
echo ""

# =============================================================================
# PASO 4: Ejecutar DDL de schemas modulares
# =============================================================================
echo -e "${YELLOW}[4/6] Ejecutando DDL de schemas modulares...${NC}"

# Buscar y ejecutar todos los archivos DDL en orden
DDL_FILES=$(find "$SCHEMAS_DIR" -name "*.sql" -type f 2>/dev/null | sort)

if [ -z "$DDL_FILES" ]; then
    echo -e "${YELLOW}  No hay archivos DDL modulares adicionales${NC}"
else
    for ddl_file in $DDL_FILES; do
        filename=$(basename "$ddl_file")
        echo -ne "  - Ejecutando ${YELLOW}$filename${NC}..."
        if psql "$DATABASE_URL" -f "$ddl_file" > /dev/null 2>&1; then
            echo -e " ${GREEN}OK${NC}"
        else
            echo -e " ${RED}ERROR${NC}"
            echo -e "${RED}Fallo al ejecutar: $ddl_file${NC}"
            exit 1
        fi
    done
fi
echo ""

# =============================================================================
# PASO 5: Ejecutar DDL legacy (si existe)
# =============================================================================
echo -e "${YELLOW}[5/6] Ejecutando DDL de schemas legacy (si existen)...${NC}"

LEGACY_DDL_DIR="$DDL_DIR/schemas"
if [ -d "$LEGACY_DDL_DIR" ]; then
    LEGACY_FILES=$(find "$LEGACY_DDL_DIR" -name "*.sql" -type f 2>/dev/null | sort)
    for ddl_file in $LEGACY_FILES; do
        filename=$(basename "$ddl_file")
        dirname=$(dirname "$ddl_file" | xargs basename)
        echo -ne "  - ${YELLOW}$dirname/$filename${NC}..."
        if psql "$DATABASE_URL" -f "$ddl_file" > /dev/null 2>&1; then
            echo -e " ${GREEN}OK${NC}"
        else
            echo -e " ${YELLOW}SKIP (puede requerir dependencias)${NC}"
        fi
    done
else
    echo -e "  No hay DDL legacy"
fi
echo ""

# =============================================================================
# PASO 6: Verificar resultado
# =============================================================================
echo -e "${YELLOW}[6/6] Verificando resultado...${NC}"
echo ""

# Contar schemas creados
SCHEMA_COUNT=$(psql "$DATABASE_URL" -t -c "
SELECT COUNT(*) FROM pg_namespace
WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'pg_temp_1', 'pg_toast_temp_1', 'public')
AND nspname NOT LIKE 'pg_%'
" | tr -d ' ')

# Contar tablas totales
TABLE_COUNT=$(psql "$DATABASE_URL" -t -c "
SELECT COUNT(*) FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema', 'public')
" | tr -d ' ')

# Mostrar resumen por schema
echo -e "${GREEN}=== RESUMEN DE CARGA LIMPIA ===${NC}"
echo ""
psql "$DATABASE_URL" -c "
SELECT
    schemaname AS \"Schema\",
    COUNT(*) AS \"Tablas\"
FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema', 'public')
GROUP BY schemaname
ORDER BY schemaname;
"

echo ""
echo -e "${GREEN}=============================================================================${NC}"
echo -e "${GREEN}   CARGA LIMPIA COMPLETADA EXITOSAMENTE${NC}"
echo -e "${GREEN}=============================================================================${NC}"
echo -e "  Schemas creados: ${YELLOW}$SCHEMA_COUNT${NC}"
echo -e "  Tablas creadas:  ${YELLOW}$TABLE_COUNT${NC}"
echo -e "${GREEN}=============================================================================${NC}"
