#!/bin/bash

# Deemah Authorization App - Docker Setup Script
# This script helps you set up the application with Docker Compose

set -e

echo "=========================================="
echo "Deemah Authorization App - Docker Setup"
echo "=========================================="
echo ""

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

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo "❌ Error: Docker Compose is not installed."
    echo "Please install Docker Compose from https://docs.docker.com/compose/install/"
    exit 1
fi

echo "✅ Docker and Docker Compose are installed"
echo ""

# Check if .env file exists
if [ ! -f .env ]; then
    echo "📝 Creating .env file from .env.example..."
    cp .env.example .env
    
    # Update DB_HOST for Docker
    if [[ "$OSTYPE" == "darwin"* ]] || [[ "$OSTYPE" == "linux-gnu"* ]]; then
        sed -i.bak 's/DB_HOST=127.0.0.1/DB_HOST=postgres/' .env
        rm .env.bak
    fi
    
    echo "✅ .env file created"
    echo ""
    echo "⚠️  Please update the following in your .env file:"
    echo "   - AWS_ACCESS_KEY_ID"
    echo "   - AWS_SECRET_ACCESS_KEY"
    echo "   - AWS_PROFILE (if using AWS profiles)"
    echo "   - AWS_BUCKET"
    echo ""
    read -p "Press Enter to continue after updating .env file..."
else
    echo "✅ .env file already exists"
fi

echo ""
echo "🏗️  Building Docker images..."
docker-compose build

echo ""
echo "🚀 Starting Docker containers..."
docker-compose up -d

echo ""
echo "⏳ Waiting for PostgreSQL to be ready..."
sleep 10

echo ""
echo "📦 Installing PHP dependencies..."
docker-compose exec -T app composer install --no-interaction

echo ""
echo "📦 Installing Node dependencies..."
docker-compose exec -T vite npm install

echo ""
echo "🔑 Generating application key..."
docker-compose exec -T app php artisan key:generate

echo ""
echo "🗄️  Running database migrations..."
docker-compose exec -T app php artisan migrate --force

echo ""
echo "🌱 Seeding database..."
docker-compose exec -T app php artisan db:seed --force

echo ""
echo "=========================================="
echo "✅ Setup Complete!"
echo "=========================================="
echo ""
echo "Your application is now running:"
echo "  🌐 Laravel App: http://localhost:8000"
echo "  ⚡ Vite Dev Server: http://localhost:5173"
echo "  🗄️  PostgreSQL: localhost:5432"
echo ""
echo "Useful commands:"
echo "  View logs:        docker-compose logs -f"
echo "  Stop services:    docker-compose down"
echo "  Restart services: docker-compose restart"
echo "  Run artisan:      docker-compose exec app php artisan [command]"
echo ""
echo "For more information, see DOCKER.md"
echo ""
