#!/bin/bash
set -e

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

# Logging functions
log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

log_step() {
    echo -e "${BLUE}⏳ $1${NC}"
}

# Function to wait for database connection
wait_for_database() {
    local max_attempts=30
    local attempt=1
    local db_host
    local db_port=5432
    
    # Extract host from DATABASE_URL
    if [[ $DATABASE_URL =~ postgresql://[^:]+:[^@]+@([^:]+):([0-9]+)/(.+) ]]; then
        db_host="${BASH_REMATCH[1]}"
        db_port="${BASH_REMATCH[2]}"
    else
        log_error "Invalid DATABASE_URL format"
        exit 1
    fi
    
    log_step "Waiting for database connection..."
    log_info "Host: $db_host, Port: $db_port"
    
    while [ $attempt -le $max_attempts ]; do
        if wait-for-it "$db_host:$db_port" -t 5 --quiet; then
            log_success "The database is ready to connect."
            return 0
        else
            log_warning "Attempt $attempt/$max_attempts: Database not ready, waiting..."
            sleep 2
            ((attempt++))
        fi
    done
    
    log_error "Failed to connect to database after $max_attempts attempts"
    exit 1
}

# Function to run migrations
run_migrations() {
    log_step "Running Drizzle migrations..."
    log_info "Using drizzle-kit migrate for versioned migrations"
    
    if node migrate.js; then
        log_success "Migrations have been successfully applied"
    else
        log_error "Error applying migrations"
        exit 1
    fi
}

# Function to validate environment variables
validate_environment() {
    log_step "Checking environment variables..."
    
    if [ -z "$DATABASE_URL" ]; then
        log_error "DATABASE_URL is not set"
        exit 1
    fi
    
    if [ -z "$NODE_ENV" ]; then
        log_warning "NODE_ENV is not set, using the default value: production"
        export NODE_ENV=production
    fi
    
    log_success "Environment variables are valid"
}

# Function to start the application
start_application() {
    log_step "Launching the application..."
    
    # Execute the main command
    exec "$@"
}

# Main execution
main() {
    log_info "=== Launching Docker Entrypoint ==="
    log_info "NODE_ENV: ${NODE_ENV:-production}"

    # Validate environment
    validate_environment

    # Wait for database
    wait_for_database
    
    # Run migrations
    run_migrations
    
    # Start the application
    start_application "$@"
}

# Handle signals for graceful shutdown
trap 'log_warning "Termination signal received, stopping application..."; exit 0' SIGTERM SIGINT

# Run main function
main "$@"
