#!/bin/bash
# Script de inicio rápido - Docker Compose optimizado
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

cd "$SCRIPT_DIR"

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

echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║  Student Enrollment System - Docker Deploy    ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"

# Verificar Docker
if ! command -v docker &> /dev/null; then
    echo -e "${RED}Error: Docker no está instalado${NC}"
    exit 1
fi

# Limpiar contenedores anteriores si existen
echo -e "\n${YELLOW}► Limpiando contenedores anteriores...${NC}"
docker compose down --remove-orphans 2>/dev/null || true

# Build con cache
echo -e "\n${YELLOW}► Construyendo imágenes (con cache)...${NC}"
DOCKER_BUILDKIT=1 docker compose build --parallel

# Iniciar servicios
echo -e "\n${YELLOW}► Iniciando servicios...${NC}"
docker compose up -d

# Esperar a que los servicios estén listos
echo -e "\n${YELLOW}► Esperando servicios...${NC}"

echo -n "  SQL Server: "
timeout 60 bash -c 'until docker compose exec -T db /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "${DB_PASSWORD:-Your_Str0ng_P@ssword!}" -Q "SELECT 1" -C &>/dev/null; do sleep 2; done' && echo -e "${GREEN}✓${NC}" || echo -e "${RED}✗${NC}"

echo -n "  API .NET:   "
timeout 60 bash -c 'until curl -sf http://localhost:5000/health &>/dev/null; do sleep 2; done' && echo -e "${GREEN}✓${NC}" || echo -e "${RED}✗${NC}"

echo -n "  Frontend:   "
timeout 30 bash -c 'until curl -sf http://localhost/ &>/dev/null; do sleep 2; done' && echo -e "${GREEN}✓${NC}" || echo -e "${RED}✗${NC}"

# Resumen
echo -e "\n${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║  ✓ Sistema desplegado correctamente           ║${NC}"
echo -e "${GREEN}╠═══════════════════════════════════════════════╣${NC}"
echo -e "${GREEN}║  Frontend:     http://localhost                ║${NC}"
echo -e "${GREEN}║  API GraphQL:  http://localhost:5000/graphql   ║${NC}"
echo -e "${GREEN}║  SQL Server:   localhost:1433                  ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"

echo -e "\n${YELLOW}Comandos útiles:${NC}"
echo "  docker compose logs -f        # Ver logs"
echo "  docker compose ps             # Ver estado"
echo "  docker compose down           # Detener todo"
echo "  docker compose restart api    # Reiniciar API"
