#!/bin/bash

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

# Configuration from environment or defaults
APP_NAME="${APP_NAME:-auth-cml}"
APP_PORT="${APP_PORT:-5004}"
DB_PORT="${DB_PORT:-3306}"

# Start timer
START_TIME=$(date +%s)

# Functions
info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if docker exists
if ! command -v docker &> /dev/null; then
    error "Docker is not installed"
    exit 1
fi

# Check docker-compose.yml exists
if [ ! -f "docker-compose.yml" ]; then
    error "docker-compose.yml not found in current directory"
    exit 1
fi

info "🐳 Starting Docker Compose deployment..."

# Build Docker image
info "Building Docker image..."
docker compose build
if [ $? -ne 0 ]; then
    error "Failed to build Docker image"
    exit 1
fi
success "Docker image built successfully"

# Remove existing containers before creating new ones
info "Removing existing containers..."
docker compose down --remove-orphans 2>/dev/null
success "Previous containers removed"

# Start containers with fresh recreation
info "Starting containers..."
docker compose up -d --force-recreate --build
if [ $? -ne 0 ]; then
    error "Failed to start containers"
    exit 1
fi
success "Containers started"

# No need to wait for MySQL - using existing cPanel database
info "Skipping database health check (using existing cPanel database)"

# Skip Prisma migrations - using existing cPanel database
info "Skipping database migrations (using existing cPanel database)"

# Optional: Seed database (if needed)

# Display deployment summary
echo ""
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ 🚀 Deployment Completed Successfully! ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
echo ""

info "Application Name: $APP_NAME"
info "Application URL: http://localhost:$APP_PORT"
info "MySQL Port: $DB_PORT"
info "Database: cmlapps_auth"
info "DB User: cmlapps_auth"

echo ""
echo -e "${YELLOW}Useful Commands:${NC}"
echo -e "  ${BLUE}View logs${NC}:           docker compose logs -f app"
echo -e "  ${BLUE}Stop services${NC}:        docker compose down"
echo -e "  ${BLUE}Stop & cleanup${NC}:       docker compose down -v"
echo -e "  ${BLUE}Run migrations${NC}:       docker compose exec app npx prisma migrate deploy"
echo -e "  ${BLUE}Prisma Studio${NC}:        docker compose exec app npx prisma studio"
echo -e "  ${BLUE}Access container${NC}:     docker compose exec app sh\n"
echo ""

# Cleanup on error
log_error_cleanup() {
    error "Deployment failed"
    info "Rolling back..."
    docker compose down 2>/dev/null
}

trap log_error_cleanup EXIT

# Calculate time
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
info "Deployment took $DURATION seconds"

trap - EXIT
