#!/bin/bash

set -e

echo "🚀 Setting up Insurance Application with Docker..."

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker is not running. Please start Docker and try again."
    exit 1
fi

# Check if docker compose is available
if ! docker compose version &> /dev/null; then
    echo "❌ docker compose is not available. Please install Docker Compose and try again."
    exit 1
fi

echo "📦 Building Docker containers..."
docker compose build

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

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

echo "📥 Installing PHP dependencies..."
docker compose exec -T insurance_app composer install --no-interaction

echo "📥 Installing Node dependencies..."
docker compose exec -T insurance_app npm install

echo "🔧 Setting up environment..."
if [ ! -f .env ]; then
    if [ -f .env.example ]; then
        docker compose exec -T insurance_app cp .env.example .env
        echo "✅ Created .env from .env.example"
    else
        echo "⚠️  No .env.example found. Please create .env manually."
    fi
fi

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

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

echo "📦 Building frontend assets..."
docker compose exec -T insurance_app npm run build

echo "✅ Setup complete!"
echo ""
echo "📋 Next steps:"
echo "   1. Update .env with your configuration"
echo "   2. Access the application at http://localhost"
echo "   3. View logs: docker compose logs -f"
echo ""
echo "🔧 Useful commands:"
echo "   - Stop: docker compose stop"
echo "   - Start: docker compose start"
echo "   - Logs: docker compose logs -f"
echo "   - Shell: docker compose exec insurance_app bash"

