#!/bin/bash

# Feuerwehr Dashboard Deployment Script
# Usage: ./deploy.sh [production|local|stop|logs|rebuild|clean]

set -e

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

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

# Helper functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

# Check if .env exists for production
check_env_file() {
    if [ ! -f .env ]; then
        log_error ".env file not found!"
        log_info "Please copy .env.example to .env and configure it:"
        log_info "  cp .env.example .env"
        exit 1
    fi
}

# Production deployment
deploy_production() {
    log_info "Starting production deployment..."
    check_env_file

    log_info "Building and starting production services..."
    docker-compose -f docker-compose.yml up -d --build

    log_info "Production deployment complete!"
    log_info "Services are running:"
    docker-compose -f docker-compose.yml ps
}

# Local development
deploy_local() {
    log_info "Starting local development environment..."

    log_info "Starting PostgreSQL database..."
    docker-compose -f docker-compose.dev.yml up -d

    log_info "Local development database is ready!"
    log_info "Connection details:"
    log_info "  Host: localhost"
    log_info "  Port: 5432"
    log_info "  Database: feuerwehr_dev"
    log_info "  User: dev_user"
    log_info "  Password: dev_password"
}

# Stop services
stop_services() {
    log_info "Stopping services..."

    if [ -f docker-compose.yml ]; then
        docker-compose -f docker-compose.yml down
        log_info "Production services stopped"
    fi

    if [ -f docker-compose.dev.yml ]; then
        docker-compose -f docker-compose.dev.yml down
        log_info "Development services stopped"
    fi
}

# Show logs
show_logs() {
    local compose_file="${1:-docker-compose.yml}"

    if [ ! -f "$compose_file" ]; then
        log_error "Compose file not found: $compose_file"
        exit 1
    fi

    log_info "Showing logs from $compose_file..."
    docker-compose -f "$compose_file" logs -f
}

# Rebuild services
rebuild_services() {
    local compose_file="${1:-docker-compose.yml}"

    if [ ! -f "$compose_file" ]; then
        log_error "Compose file not found: $compose_file"
        exit 1
    fi

    log_info "Rebuilding services from $compose_file..."
    docker-compose -f "$compose_file" up -d --build --force-recreate

    log_info "Rebuild complete!"
}

# Clean up
clean_all() {
    log_warn "This will remove all containers, volumes, and images for this project."
    read -p "Are you sure? (y/N) " -n 1 -r
    echo

    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "Cleaning up..."

        # Stop all services
        docker-compose -f docker-compose.yml down -v 2>/dev/null || true
        docker-compose -f docker-compose.dev.yml down -v 2>/dev/null || true

        # Remove project-specific images
        docker images | grep feuerwehr | awk '{print $3}' | xargs docker rmi -f 2>/dev/null || true

        log_info "Cleanup complete!"
    else
        log_info "Cleanup cancelled"
    fi
}

# Main script
case "${1:-}" in
    production)
        deploy_production
        ;;
    local)
        deploy_local
        ;;
    stop)
        stop_services
        ;;
    logs)
        show_logs "${2:-docker-compose.yml}"
        ;;
    rebuild)
        rebuild_services "${2:-docker-compose.yml}"
        ;;
    clean)
        clean_all
        ;;
    *)
        echo "Usage: $0 {production|local|stop|logs|rebuild|clean}"
        echo ""
        echo "Commands:"
        echo "  production  - Deploy production environment (all services)"
        echo "  local       - Start local development database only"
        echo "  stop        - Stop all services"
        echo "  logs        - Show logs (append 'docker-compose.dev.yml' for dev logs)"
        echo "  rebuild     - Rebuild and restart services"
        echo "  clean       - Remove all containers, volumes, and images"
        echo ""
        echo "Examples:"
        echo "  $0 local                           # Start dev database"
        echo "  $0 production                      # Deploy production"
        echo "  $0 logs                            # Show production logs"
        echo "  $0 logs docker-compose.dev.yml     # Show dev logs"
        echo "  $0 rebuild docker-compose.dev.yml  # Rebuild dev services"
        exit 1
        ;;
esac
