#!/bin/bash

# CBT Platform - Docker Development Environment Script
# This script helps manage the Docker Compose development environment

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

# Function to print colored output
print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

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

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Function to check if Docker is running
check_docker() {
    if ! docker info > /dev/null 2>&1; then
        print_error "Docker is not running. Please start Docker first."
        exit 1
    fi
}

# Function to check if .env.docker exists
check_env_file() {
    if [ ! -f .env.docker ]; then
        print_error ".env.docker file not found!"
        print_info "Creating .env.docker from defaults..."
        cp .env.docker.example .env.docker 2>/dev/null || true
    fi
}

# Function to start the environment
start_environment() {
    print_info "Starting CBT Platform development environment..."
    check_docker
    check_env_file

    # Load environment variables
    export $(cat .env.docker | grep -v '^#' | xargs)

    docker-compose up -d

    print_success "Environment started successfully!"
    echo ""
    print_info "Services:"
    echo "  • PostgreSQL:     localhost:${DB_PORT:-5432}"
    echo "  • Redis:          localhost:${REDIS_PORT:-6379}"
    echo "  • Golang API:     localhost:${API_PORT:-8080}"
    echo "  • Adminer UI:     http://localhost:${ADMINER_PORT:-8081}"
    echo ""
    print_info "Run './docker-dev.sh logs' to view logs"
    print_info "Run './docker-dev.sh stop' to stop the environment"
}

# Function to stop the environment
stop_environment() {
    print_info "Stopping CBT Platform development environment..."
    docker-compose down
    print_success "Environment stopped successfully!"
}

# Function to restart the environment
restart_environment() {
    print_info "Restarting CBT Platform development environment..."
    stop_environment
    sleep 2
    start_environment
}

# Function to view logs
view_logs() {
    service=${1:-}
    if [ -z "$service" ]; then
        docker-compose logs -f
    else
        docker-compose logs -f "$service"
    fi
}

# Function to show status
show_status() {
    print_info "CBT Platform environment status:"
    docker-compose ps
}

# Function to run database migrations
run_migrations() {
    print_info "Running database migrations..."
    docker-compose exec api go run cmd/migrate/main.go
    print_success "Migrations completed!"
}

# Function to create database backup
backup_database() {
    backup_file="backup_$(date +%Y%m%d_%H%M%S).sql"
    print_info "Creating database backup: $backup_file"
    docker-compose exec -T postgres pg_dump -U postgres cbt > "$backup_file"
    print_success "Backup created: $backup_file"
}

# Function to restore database backup
restore_database() {
    backup_file=${1:-}
    if [ -z "$backup_file" ]; then
        print_error "Please specify backup file: ./docker-dev.sh restore <backup-file>"
        exit 1
    fi

    if [ ! -f "$backup_file" ]; then
        print_error "Backup file not found: $backup_file"
        exit 1
    fi

    print_info "Restoring database from: $backup_file"
    docker-compose exec -T postgres psql -U postgres cbt < "$backup_file"
    print_success "Database restored successfully!"
}

# Function to clean everything (remove volumes)
clean_all() {
    print_warning "This will remove all containers, volumes, and data!"
    read -p "Are you sure? (yes/no): " confirm

    if [ "$confirm" = "yes" ]; then
        print_info "Cleaning up..."
        docker-compose down -v
        print_success "Cleanup completed!"
    else
        print_info "Cleanup cancelled."
    fi
}

# Function to rebuild containers
rebuild_containers() {
    print_info "Rebuilding containers..."
    docker-compose build --no-cache
    print_success "Containers rebuilt!"
}

# Function to show help
show_help() {
    cat << EOF
CBT Platform - Docker Development Environment

Usage: ./docker-dev.sh [COMMAND]

Commands:
  start           Start the development environment
  stop            Stop the development environment
  restart         Restart the development environment
  status          Show status of all services
  logs [service]  View logs (optional: specify service name)
  rebuild         Rebuild all containers
  migrate         Run database migrations
  backup          Create database backup
  restore <file>  Restore database from backup
  clean           Remove all containers, volumes, and data
  help            Show this help message

Examples:
  ./docker-dev.sh start              # Start all services
  ./docker-dev.sh logs api           # View API logs
  ./docker-dev.sh restore backup.sql # Restore database

Services:
  • postgres   - PostgreSQL 16 database
  • redis      - Redis 7 cache
  • api        - Golang API with hot reload
  • adminer    - Database management UI

EOF
}

# Main script logic
case "${1:-}" in
    start)
        start_environment
        ;;
    stop)
        stop_environment
        ;;
    restart)
        restart_environment
        ;;
    status)
        show_status
        ;;
    logs)
        view_logs "${2:-}"
        ;;
    rebuild)
        rebuild_containers
        ;;
    migrate)
        run_migrations
        ;;
    backup)
        backup_database
        ;;
    restore)
        restore_database "$2"
        ;;
    clean)
        clean_all
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        print_error "Unknown command: ${1:-}"
        echo ""
        show_help
        exit 1
        ;;
esac
