#!/bin/bash

# Docker build script for eslogad-backend

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

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

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

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# Help function
show_help() {
    echo "Usage: $0 [OPTION]"
    echo "Build and manage Docker containers for eslogad-backend"
    echo ""
    echo "Options:"
    echo "  build       Build the Docker image"
    echo "  run         Run the production container"
    echo "  dev         Run development environment with live reload"
    echo "  migrate     Run database migrations"
    echo "  stop        Stop all containers"
    echo "  clean       Remove containers and images"
    echo "  logs        Show container logs"
    echo "  help        Show this help message"
    echo ""
}

# Build Docker image
build_image() {
    log_info "Building eslogad-backend Docker image..."
    
    # Check if Go build works locally first (optional quick test)
    if command -v go &> /dev/null; then
        log_info "Testing Go build locally first..."
        if go build -o /tmp/test-build cmd/server/main.go 2>/dev/null; then
            log_success "Local Go build test passed"
            rm -f /tmp/test-build
        else
            log_warning "Local Go build test failed, but continuing with Docker build..."
        fi
    fi
    
    # Build the image with production target
    docker build \
        --target production \
        -t eslogad-backend:latest \
        -t eslogad-backend:$(date +%Y%m%d-%H%M%S) \
        .
    
    if [ $? -eq 0 ]; then
        log_success "Docker image built successfully!"
    else
        log_error "Failed to build Docker image"
        log_info "Make sure you're using Go 1.21+ and all dependencies are available"
        exit 1
    fi
}

# Run production container
run_container() {
    log_info "Starting production containers..."
    
    # Start the containers
    docker-compose up -d
    
    if [ $? -eq 0 ]; then
        log_success "Containers started successfully!"
        log_info "Backend API available at: http://localhost:3300"
        log_info "Database available at: localhost:5432"
        log_info "Redis available at: localhost:6379"
        log_info ""
        log_info "Use 'docker-compose logs -f backend' to view logs"
    else
        log_error "Failed to start containers"
        exit 1
    fi
}

# Run development environment
run_dev() {
    log_info "Starting development environment..."
    
    # Start development containers
    docker-compose --profile dev up -d
    
    if [ $? -eq 0 ]; then
        log_success "Development environment started!"
        log_info "Backend API (dev) available at: http://localhost:3001"
        log_info "Backend API (prod) available at: http://localhost:3300"
        log_info ""
        log_info "Use 'docker-compose logs -f backend-dev' to view development logs"
    else
        log_error "Failed to start development environment"
        exit 1
    fi
}

# Run migrations
run_migrations() {
    log_info "Running database migrations..."
    
    # Ensure database is running
    docker-compose up -d postgres
    sleep 5
    
    # Run migrations
    docker-compose --profile migrate up migrate
    
    if [ $? -eq 0 ]; then
        log_success "Migrations completed successfully!"
    else
        log_warning "Migrations may have failed or are already up to date"
    fi
}

# Stop containers
stop_containers() {
    log_info "Stopping all containers..."
    
    docker-compose down
    
    if [ $? -eq 0 ]; then
        log_success "All containers stopped"
    else
        log_error "Failed to stop containers"
        exit 1
    fi
}

# Clean up containers and images
clean_up() {
    log_warning "This will remove all containers, networks, and images related to this project"
    read -p "Are you sure? (y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "Cleaning up containers and images..."
        
        # Stop and remove containers
        docker-compose down -v --remove-orphans
        
        # Remove images
        docker rmi eslogad-backend:latest || true
        docker rmi $(docker images eslogad-backend -q) || true
        
        # Remove unused networks and volumes
        docker network prune -f || true
        docker volume prune -f || true
        
        log_success "Cleanup completed"
    else
        log_info "Cleanup cancelled"
    fi
}

# Show logs
show_logs() {
    log_info "Showing container logs..."
    
    # Show logs for all services
    docker-compose logs -f
}

# Main script logic
case "${1:-help}" in
    "build")
        build_image
        ;;
    "run")
        build_image
        run_container
        ;;
    "dev")
        run_dev
        ;;
    "migrate")
        run_migrations
        ;;
    "stop")
        stop_containers
        ;;
    "clean")
        clean_up
        ;;
    "logs")
        show_logs
        ;;
    "help"|*)
        show_help
        ;;
esac 