#!/bin/bash
# ============================================================================
# ERP GENERIC - RESET DATABASE SCRIPT
# ============================================================================
# Description: Drops and recreates the database with fresh data
# Usage: ./scripts/reset-database.sh [--no-seeds] [--env dev|prod] [--force]
#
# Por defecto:
#   - Carga DDL completo
#   - Carga seeds de desarrollo (dev)
#   - Pide confirmación
#
# Opciones:
#   --no-seeds    No cargar seeds después del DDL
#   --env ENV     Ambiente de seeds: dev (default) o prod
#   --force       No pedir confirmación (para CI/CD)
# ============================================================================

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Defaults - Seeds activados por defecto
WITH_SEEDS=true
ENV="dev"
FORCE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --no-seeds)
            WITH_SEEDS=false
            shift
            ;;
        --env)
            ENV="$2"
            shift 2
            ;;
        --force)
            FORCE=true
            shift
            ;;
        *)
            shift
            ;;
    esac
done

echo -e "${YELLOW}============================================${NC}"
echo -e "${YELLOW}   ERP GENERIC - RESET DATABASE${NC}"
echo -e "${YELLOW}============================================${NC}"
echo ""
echo -e "Ambiente: ${GREEN}$ENV${NC}"
echo -e "Seeds:    ${GREEN}$WITH_SEEDS${NC}"
echo ""
echo -e "${RED}WARNING: This will DELETE all data and recreate the database!${NC}"
echo ""

if [ "$FORCE" = false ]; then
    read -p "Are you sure you want to reset? (y/N): " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo "Aborted."
        exit 0
    fi
fi

# Drop database
echo ""
echo -e "${BLUE}Step 1: Dropping database...${NC}"
"$SCRIPT_DIR/drop-database.sh" --force

# Create database (DDL)
echo ""
echo -e "${BLUE}Step 2: Creating database (DDL)...${NC}"
"$SCRIPT_DIR/create-database.sh"

# Load seeds (por defecto)
if [ "$WITH_SEEDS" = true ]; then
    echo ""
    echo -e "${BLUE}Step 3: Loading seed data ($ENV)...${NC}"
    "$SCRIPT_DIR/load-seeds.sh" "$ENV"
else
    echo ""
    echo -e "${YELLOW}Step 3: Skipping seeds (--no-seeds)${NC}"
fi

echo ""
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN}   DATABASE RESET COMPLETE!${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""
echo -e "Resumen:"
echo -e "  - DDL ejecutados: ${GREEN}15 archivos${NC}"
echo -e "  - Seeds cargados: ${GREEN}$WITH_SEEDS ($ENV)${NC}"
echo ""
