#!/bin/bash

# docker-test.sh - Test Docker builds for Feuerwehr Dashboard
# This script tests building backend and frontend Docker images locally

set -e  # Exit on any error

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

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

# Log 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"
}

# Print header
print_header() {
    echo ""
    echo "========================================"
    echo "  Feuerwehr Dashboard - Docker Build Test"
    echo "========================================"
    echo ""
}

# Check if Docker is available
check_docker() {
    log_info "Checking Docker availability..."

    if ! command -v docker &> /dev/null; then
        log_error "Docker is not installed or not in PATH"
        log_info "Please install Docker from https://docs.docker.com/get-docker/"
        exit 1
    fi

    if ! docker info &> /dev/null; then
        log_error "Docker daemon is not running"
        log_info "Please start Docker and try again"
        exit 1
    fi

    log_success "Docker is available"
    docker --version
    echo ""
}

# Test backend Docker build
test_backend_build() {
    log_info "Testing Backend Docker build..."
    echo ""

    cd "${SCRIPT_DIR}/backend"

    # Check if Dockerfile exists
    if [ ! -f "Dockerfile" ]; then
        log_error "Backend Dockerfile not found at ${SCRIPT_DIR}/backend/Dockerfile"
        return 1
    fi

    # Check if package.json exists
    if [ ! -f "package.json" ]; then
        log_error "Backend package.json not found"
        return 1
    fi

    log_info "Building backend image (feuerwehr-backend-test)..."

    # Build the image
    if docker build \
        --tag feuerwehr-backend-test:latest \
        --file Dockerfile \
        --progress=plain \
        .; then
        log_success "Backend image built successfully"

        # Get image size
        IMAGE_SIZE=$(docker images feuerwehr-backend-test:latest --format "{{.Size}}")
        log_info "Backend image size: ${IMAGE_SIZE}"

        return 0
    else
        log_error "Backend image build failed"
        return 1
    fi
}

# Test frontend Docker build
test_frontend_build() {
    log_info "Testing Frontend Docker build..."
    echo ""

    cd "${SCRIPT_DIR}/frontend"

    # Check if Dockerfile exists
    if [ ! -f "Dockerfile" ]; then
        log_error "Frontend Dockerfile not found at ${SCRIPT_DIR}/frontend/Dockerfile"
        return 1
    fi

    # Check if package.json exists
    if [ ! -f "package.json" ]; then
        log_error "Frontend package.json not found"
        return 1
    fi

    # Check if nginx.conf exists
    if [ ! -f "nginx.conf" ]; then
        log_warning "Frontend nginx.conf not found"
    fi

    log_info "Building frontend image (feuerwehr-frontend-test)..."

    # Build the image with build args
    if docker build \
        --tag feuerwehr-frontend-test:latest \
        --file Dockerfile \
        --build-arg VITE_API_URL=http://localhost:3000 \
        --build-arg VITE_APP_NAME="Feuerwehr Dashboard" \
        --build-arg VITE_APP_VERSION="1.0.0" \
        --progress=plain \
        .; then
        log_success "Frontend image built successfully"

        # Get image size
        IMAGE_SIZE=$(docker images feuerwehr-frontend-test:latest --format "{{.Size}}")
        log_info "Frontend image size: ${IMAGE_SIZE}"

        return 0
    else
        log_error "Frontend image build failed"
        return 1
    fi
}

# Cleanup test images
cleanup_images() {
    log_info "Cleaning up test images..."

    # Remove backend test image
    if docker images -q feuerwehr-backend-test:latest &> /dev/null; then
        docker rmi feuerwehr-backend-test:latest &> /dev/null || true
        log_success "Removed backend test image"
    fi

    # Remove frontend test image
    if docker images -q feuerwehr-frontend-test:latest &> /dev/null; then
        docker rmi feuerwehr-frontend-test:latest &> /dev/null || true
        log_success "Removed frontend test image"
    fi

    echo ""
}

# Print summary
print_summary() {
    echo ""
    echo "========================================"
    echo "  Build Test Summary"
    echo "========================================"
    echo ""

    if [ $BACKEND_BUILD_SUCCESS -eq 1 ]; then
        log_success "Backend: Build successful"
    else
        log_error "Backend: Build failed"
    fi

    if [ $FRONTEND_BUILD_SUCCESS -eq 1 ]; then
        log_success "Frontend: Build successful"
    else
        log_error "Frontend: Build failed"
    fi

    echo ""

    if [ $BACKEND_BUILD_SUCCESS -eq 1 ] && [ $FRONTEND_BUILD_SUCCESS -eq 1 ]; then
        log_success "All builds passed!"
        echo ""
        log_info "Next steps:"
        echo "  1. Review .env.example and create .env file"
        echo "  2. Set required environment variables (POSTGRES_PASSWORD, JWT_SECRET)"
        echo "  3. Run: docker-compose up -d"
        echo ""
        return 0
    else
        log_error "Some builds failed. Please review the errors above."
        echo ""
        return 1
    fi
}

# Main execution
main() {
    print_header

    # Initialize success flags
    BACKEND_BUILD_SUCCESS=0
    FRONTEND_BUILD_SUCCESS=0

    # Check Docker
    check_docker

    # Test backend build
    if test_backend_build; then
        BACKEND_BUILD_SUCCESS=1
    fi
    echo ""

    # Test frontend build
    if test_frontend_build; then
        FRONTEND_BUILD_SUCCESS=1
    fi
    echo ""

    # Ask if user wants to cleanup
    read -p "Do you want to remove test images? (y/n) " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        cleanup_images
    else
        log_info "Test images kept for inspection"
        echo "  - feuerwehr-backend-test:latest"
        echo "  - feuerwehr-frontend-test:latest"
        echo ""
    fi

    # Print summary
    print_summary
}

# Run main function
main "$@"
