#!/bin/bash

# Setup script for Docker local development environment
# This script prepares the environment and creates necessary files

set -e  # Exit on any error

echo "🚀 Setting up Docker environment for local development..."

# 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_status() {
    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"
}

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    print_error "Docker is not installed. Please install Docker first."
    echo "Visit: https://docs.docker.com/get-docker/"
    exit 1
fi

# Check if Docker Compose is available
if ! docker compose version &> /dev/null && ! docker-compose --version &> /dev/null; then
    print_error "Docker Compose is not available. Please install Docker Compose."
    exit 1
fi

print_success "Docker and Docker Compose are installed"

# Check if Docker daemon is running
if ! docker info &> /dev/null; then
    print_error "Docker daemon is not running. Please start Docker first."
    exit 1
fi

print_success "Docker daemon is running"

# Create .env.local if it doesn't exist
if [ ! -f ".env.local" ]; then
    print_status "Creating .env.local file..."
    
    # Generate a random secret for BETTER_AUTH_SECRET
    BETTER_AUTH_SECRET=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-32)
    
    cat > .env.local << EOF
# Magasinet KBH - Local Development Environment
# This file contains all configuration values for local development
# Generated by setup_env.sh - DO NOT EDIT MANUALLY

# =============================================================================
# DATABASE CONFIGURATION
# =============================================================================
DATABASE_URL=postgresql://postgres:postgres_password@postgres:5432/magasinetkbh
DATABASE_URL_DOCKER=postgresql://postgres:postgres_password@postgres:5432/magasinetkbh
DATABASE_URL_LOCAL=postgresql://postgres:postgres_password@localhost:5432/magasinetkbh
POSTGRES_DB=magasinetkbh
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres_password
POSTGRES_PORT=5432

# =============================================================================
# AUTHENTICATION CONFIGURATION
# =============================================================================
BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET}
BETTER_AUTH_URL=http://localhost:3000
BETTER_AUTH_EMAIL=admin@magasinetkbh.dk
BETTER_AUTH_DOMAIN=.localhost
BETTER_AUTH_EMAIL_PASSWORD=your-app-password

# =============================================================================
# APPLICATION CONFIGURATION
# =============================================================================
NEXT_PUBLIC_APP_URL=http://localhost:3000
NODE_ENV=development
APP_PORT=3000

# =============================================================================
# MIGRATION CONFIGURATION
# =============================================================================
# Migrations are now always used

# =============================================================================
# EMAIL CONFIGURATION (Mailpit for local testing)
# =============================================================================
SMTP_HOST=mailpit
SMTP_PORT=1025
SMTP_SECURE=false
SMTP_USER=""
SMTP_PASS=""
MAILPIT_WEB_PORT=8025
MAILPIT_SMTP_PORT=1025

# =============================================================================
# S3/STORAGE CONFIGURATION (MinIO for local development)
# =============================================================================
S3_ENDPOINT=http://minio:9000
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin123
S3_BUCKET_NAME=magasinetkbh-uploads
S3_REGION=us-east-1
S3_PUBLIC_URL=http://localhost:9000
S3_INTERNAL_URL=http://minio:9000
MINIO_API_PORT=9000
MINIO_CONSOLE_PORT=9001

# =============================================================================
# DOCKER CONFIGURATION
# =============================================================================
# These are used by Docker Compose and setup scripts
DOCKER_NETWORK=app-network
DOCKER_VOLUME_POSTGRES=postgres_data
DOCKER_VOLUME_MINIO=minio_data
EOF
    print_success "Created .env.local with secure auto-generated secrets"
else
    print_warning ".env.local already exists, skipping creation"
fi

# Check if pnpm is installed for dependency installation
if command -v pnpm &> /dev/null; then
    print_status "Installing Node.js dependencies with pnpm..."
    pnpm install
    print_success "Dependencies installed"
elif command -v npm &> /dev/null; then
    print_warning "pnpm not found, but npm is available."
    print_warning "This project uses pnpm. Please install pnpm first:"
    print_warning "  npm install -g pnpm"
    print_warning "Then run this script again."
    exit 1
else
    print_warning "Neither pnpm nor npm found. Skipping dependency installation."
    print_warning "Please install pnpm: npm install -g pnpm"
    print_warning "Then run this script again."
    exit 1
fi

# Docker Compose will create networks automatically, so we don't need to create them manually

# Load environment variables from .env.local for Docker Compose
if [ -f ".env.local" ]; then
    print_status "Loading environment variables from .env.local..."
    set -a  # automatically export all variables
    source .env.local
    set +a  # stop automatically exporting
fi

# Pull required Docker images
print_status "Pulling required Docker images..."
docker compose -f infrastructure/docker/docker-compose.yml pull

print_success "Docker environment setup completed!"
echo ""
echo "📋 Next steps:"
echo "  1. Run './infrastructure/start_docker.sh' to start the application"
echo "  2. Visit http://localhost:3000 to access the application"
echo "  3. Visit http://localhost:8025 to access Mailpit (email testing)"
echo "  4. Visit http://localhost:9001 to access MinIO console"
echo "  5. Run './infrastructure/stop_docker.sh' to stop all services"
echo ""
echo "🔧 Configuration:"
echo "  - Database: PostgreSQL on port 5432"
echo "  - Application: Next.js on port 3000"
echo "  - File Storage: MinIO on port 9000 (API) and 9001 (Console)"
echo "  - Email Testing: Mailpit on port 8025"
echo "  - Environment file: .env.local"
echo "  - Migrations: Automatic (using drizzle-kit migrate)"
echo ""
print_success "Setup complete! 🎉"