#!/bin/bash

# ============================================
# Docker Build & Deployment Script
# For Mawidi Site - Next.js Application
# ============================================

set -e  # Exit on error

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

# Configuration
PROJECT_NAME="mawidi-site"
REGISTRY_URL="${DOCKER_REGISTRY:-}"  # Set DOCKER_REGISTRY env var if using private registry
VERSION="${VERSION:-$(date +%Y%m%d-%H%M%S)}"

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

show_usage() {
    echo "Usage: ./docker-build.sh [COMMAND] [OPTIONS]"
    echo ""
    echo "Commands:"
    echo "  build-dev      Build development image"
    echo "  build-prod     Build production image"
    echo "  run-dev        Run development container"
    echo "  run-prod       Run production container"
    echo "  push           Push images to registry"
    echo "  clean          Clean up containers and images"
    echo "  logs           Show container logs"
    echo "  shell          Open shell in container"
    echo "  test           Run tests in container"
    echo ""
    echo "Options:"
    echo "  --no-cache     Build without cache"
    echo "  --version      Specify version tag"
    echo ""
}

# Check Docker installation
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed"
        exit 1
    fi
    print_info "Docker version: $(docker --version)"
}

# Build development image
build_dev() {
    print_info "Building development image..."

    docker build \
        ${NO_CACHE} \
        -f Dockerfile.dev \
        -t ${PROJECT_NAME}:dev \
        -t ${PROJECT_NAME}:dev-${VERSION} \
        .

    print_success "Development image built successfully"
}

# Build production image
build_prod() {
    print_info "Building production image..."

    # Load environment variables if .env file exists
    if [ -f .env ]; then
        export $(cat .env | grep -v '^#' | xargs)
    fi

    docker build \
        ${NO_CACHE} \
        -f Dockerfile \
        -t ${PROJECT_NAME}:latest \
        -t ${PROJECT_NAME}:${VERSION} \
        --build-arg NEXT_PUBLIC_API_URL="${NEXT_PUBLIC_API_URL}" \
        --build-arg NEXT_PUBLIC_APP_URL="${NEXT_PUBLIC_APP_URL}" \
        --build-arg NEXT_PUBLIC_WHATSAPP_NUMBER="${NEXT_PUBLIC_WHATSAPP_NUMBER}" \
        --build-arg NEXT_PUBLIC_GA_ID="${NEXT_PUBLIC_GA_ID}" \
        --build-arg NEXT_PUBLIC_STRIPE_PUBLIC_KEY="${NEXT_PUBLIC_STRIPE_PUBLIC_KEY}" \
        --build-arg NEXT_PUBLIC_POSTHOG_KEY="${NEXT_PUBLIC_POSTHOG_KEY}" \
        .

    print_success "Production image built successfully"
    print_info "Image size: $(docker images ${PROJECT_NAME}:latest --format 'size: {{.Size}}')"
}

# Run development container
run_dev() {
    print_info "Starting development container..."

    # Stop existing container if running
    docker-compose stop mawidi-dev 2>/dev/null || true

    # Start development service
    docker-compose up -d mawidi-dev

    print_success "Development container started"
    print_info "Application available at: http://localhost:3000"
    print_info "To view logs: docker-compose logs -f mawidi-dev"
}

# Run production container
run_prod() {
    print_info "Starting production container..."

    # Stop existing container if running
    docker-compose stop mawidi-prod 2>/dev/null || true

    # Start production service
    docker-compose up -d mawidi-prod

    print_success "Production container started"
    print_info "Application available at: http://localhost:9000"
    print_info "To view logs: docker-compose logs -f mawidi-prod"
}

# Push images to registry
push_images() {
    if [ -z "$REGISTRY_URL" ]; then
        print_error "DOCKER_REGISTRY environment variable not set"
        exit 1
    fi

    print_info "Pushing images to registry: $REGISTRY_URL"

    # Tag images for registry
    docker tag ${PROJECT_NAME}:latest ${REGISTRY_URL}/${PROJECT_NAME}:latest
    docker tag ${PROJECT_NAME}:${VERSION} ${REGISTRY_URL}/${PROJECT_NAME}:${VERSION}

    # Push to registry
    docker push ${REGISTRY_URL}/${PROJECT_NAME}:latest
    docker push ${REGISTRY_URL}/${PROJECT_NAME}:${VERSION}

    print_success "Images pushed successfully"
}

# Clean up containers and images
clean_up() {
    print_warning "Cleaning up Docker resources..."

    # Stop all project containers
    docker-compose down -v

    # Remove project images
    docker images | grep ${PROJECT_NAME} | awk '{print $3}' | xargs -r docker rmi -f

    # Prune system
    docker system prune -f

    print_success "Cleanup complete"
}

# Show container logs
show_logs() {
    SERVICE=${2:-mawidi-prod}
    docker-compose logs -f ${SERVICE}
}

# Open shell in container
open_shell() {
    SERVICE=${2:-mawidi-prod}
    docker-compose exec ${SERVICE} /bin/sh
}

# Run tests in container
run_tests() {
    print_info "Running tests in container..."

    docker run --rm \
        -v $(pwd):/app \
        ${PROJECT_NAME}:dev \
        npm test

    print_success "Tests completed"
}

# Main script logic
check_docker

# Parse command line arguments
COMMAND=$1
NO_CACHE=""

# Check for options
for arg in "$@"; do
    case $arg in
        --no-cache)
            NO_CACHE="--no-cache"
            ;;
        --version=*)
            VERSION="${arg#*=}"
            ;;
    esac
done

# Execute command
case $COMMAND in
    build-dev)
        build_dev
        ;;
    build-prod)
        build_prod
        ;;
    run-dev)
        run_dev
        ;;
    run-prod)
        run_prod
        ;;
    push)
        push_images
        ;;
    clean)
        clean_up
        ;;
    logs)
        show_logs "$@"
        ;;
    shell)
        open_shell "$@"
        ;;
    test)
        run_tests
        ;;
    *)
        show_usage
        exit 1
        ;;
esac