#!/bin/bash

# destroy_docker.sh - Comprehensive Docker infrastructure cleanup script
# This script destroys all Docker containers, volumes, networks, and images created by infra:setup

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}[INFO]${NC} $1"
}

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

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

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

print_header() {
    echo -e "${BLUE}🧹 Destroying Docker infrastructure for local development...${NC}"
}

# 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 and try again."
        exit 1
    fi
}

# Function to stop and remove containers
stop_containers() {
    print_info "Stopping all running containers..."
    
    # Stop containers using the compose file
    if [ -f "infrastructure/docker/docker-compose.yml" ]; then
        docker compose -f infrastructure/docker/docker-compose.yml down --remove-orphans 2>/dev/null || true
    fi
    
    # Stop any remaining containers that might be running
    local containers=$(docker ps -q)
    if [ -n "$containers" ]; then
        print_warning "Found additional running containers, stopping them..."
        docker stop $containers 2>/dev/null || true
    fi
    
    print_success "All containers stopped"
}

# Function to remove containers
remove_containers() {
    print_info "Removing all containers..."
    
    # Remove containers using the compose file
    if [ -f "infrastructure/docker/docker-compose.yml" ]; then
        docker compose -f infrastructure/docker/docker-compose.yml rm -f 2>/dev/null || true
    fi
    
    # Remove any remaining containers
    local containers=$(docker ps -aq)
    if [ -n "$containers" ]; then
        docker rm $containers 2>/dev/null || true
    fi
    
    print_success "All containers removed"
}

# Function to remove volumes
remove_volumes() {
    print_info "Removing all volumes..."
    
    # Remove volumes using the compose file
    if [ -f "infrastructure/docker/docker-compose.yml" ]; then
        docker compose -f infrastructure/docker/docker-compose.yml down -v 2>/dev/null || true
    fi
    
    # Remove any remaining volumes
    local volumes=$(docker volume ls -q)
    if [ -n "$volumes" ]; then
        docker volume rm $volumes 2>/dev/null || true
    fi
    
    print_success "All volumes removed"
}

# Function to remove networks
remove_networks() {
    print_info "Removing custom networks..."
    
    # Remove networks using the compose file
    if [ -f "infrastructure/docker/docker-compose.yml" ]; then
        docker compose -f infrastructure/docker/docker-compose.yml down --remove-orphans 2>/dev/null || true
    fi
    
    # Remove any remaining custom networks (except default ones)
    local networks=$(docker network ls --filter type=custom -q)
    if [ -n "$networks" ]; then
        docker network rm $networks 2>/dev/null || true
    fi
    
    print_success "Custom networks removed"
}

# Function to remove images
remove_images() {
    print_info "Removing Docker images..."
    
    # Remove images built by this project
    local project_images=$(docker images --filter "reference=magasinetkbh*" -q)
    if [ -n "$project_images" ]; then
        docker rmi $project_images 2>/dev/null || true
    fi
    
    # Remove any dangling images
    local dangling_images=$(docker images -f "dangling=true" -q)
    if [ -n "$dangling_images" ]; then
        docker rmi $dangling_images 2>/dev/null || true
    fi
    
    print_success "Project images removed"
}

# Function to clean up system
cleanup_system() {
    print_info "Cleaning up Docker system..."
    
    # Remove unused containers, networks, images, and build cache
    docker system prune -f 2>/dev/null || true
    
    # Remove unused volumes
    docker volume prune -f 2>/dev/null || true
    
    print_success "Docker system cleaned up"
}

# Function to show what will be removed
show_cleanup_preview() {
    print_info "Cleanup preview:"
    
    echo "Containers to be removed:"
    docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Image}}" 2>/dev/null || echo "  No containers found"
    
    echo ""
    echo "Volumes to be removed:"
    docker volume ls --format "table {{.Name}}\t{{.Driver}}" 2>/dev/null || echo "  No volumes found"
    
    echo ""
    echo "Images to be removed:"
    docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" 2>/dev/null || echo "  No images found"
    
    echo ""
}

# Function to prompt for confirmation
confirm_destroy() {
    echo ""
    print_warning "This will destroy ALL Docker containers, volumes, networks, and images."
    print_warning "This action cannot be undone!"
    echo ""
    
    read -p "Are you sure you want to continue? (y/N): " -n 1 -r
    echo ""
    
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_info "Operation cancelled."
        exit 0
    fi
}

# Main execution
main() {
    print_header
    
    # Check if Docker is running
    check_docker
    
    # Show what will be cleaned up
    show_cleanup_preview
    
    # Confirm before proceeding
    confirm_destroy
    
    # Execute cleanup steps
    stop_containers
    remove_containers
    remove_volumes
    remove_networks
    remove_images
    cleanup_system
    
    print_success "🎉 Docker infrastructure completely destroyed!"
    print_info "All containers, volumes, networks, and images have been removed."
    print_info "You can now run 'pnpm infra:setup' to recreate the infrastructure."
}

# Handle command line arguments
case "${1:-}" in
    --force|-f)
        # Skip confirmation for automated scripts
        print_header
        check_docker
        stop_containers
        remove_containers
        remove_volumes
        remove_networks
        remove_images
        cleanup_system
        print_success "🎉 Docker infrastructure completely destroyed (forced)!"
        ;;
    --help|-h)
        echo "Usage: $0 [OPTIONS]"
        echo ""
        echo "Options:"
        echo "  --force, -f    Skip confirmation prompt"
        echo "  --help, -h     Show this help message"
        echo ""
        echo "This script destroys all Docker infrastructure created by infra:setup"
        ;;
    *)
        main
        ;;
esac
