#!/bin/bash
set -e

echo "🚀 Setting up Global Gala Laravel backend workspace..."

# Check for required tools
if ! command -v php &> /dev/null; then
    echo "❌ Error: PHP is not installed. Please install PHP before continuing."
    exit 1
fi

if ! command -v composer &> /dev/null; then
    echo "❌ Error: Composer is not installed. Please install Composer before continuing."
    exit 1
fi

if ! command -v mysql &> /dev/null; then
    echo "⚠️  Warning: MySQL is not installed. You'll need MySQL for the database."
fi

# Copy environment file if it doesn't exist
if [ ! -f .env ]; then
    echo "📋 Copying .env.example to .env..."
    cp .env.example .env
    echo "⚠️  Please configure your .env file with database credentials and other settings."
else
    echo "✅ .env file already exists"
fi

# Install PHP dependencies
echo "📦 Installing Composer dependencies..."
composer install --no-interaction --prefer-dist

# Generate application key if needed
if ! grep -q "APP_KEY=base64:" .env; then
    echo "🔑 Generating application key..."
    php artisan key:generate
else
    echo "✅ Application key already set"
fi

# Install Node.js dependencies (for asset compilation)
if [ -f package.json ]; then
    if command -v npm &> /dev/null; then
        echo "📦 Installing npm dependencies..."
        npm install
    else
        echo "⚠️  Warning: npm not found. Skipping npm install."
    fi
fi

# Check database connection
echo "🔍 Checking database configuration..."
if php artisan db:show 2>/dev/null; then
    echo "✅ Database connection successful"

    # Run migrations
    echo "🗄️  Running database migrations..."
    php artisan migrate --force
else
    echo "⚠️  Warning: Could not connect to database. Please verify your .env database settings:"
    echo "   - DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD"
    echo "   You can run migrations manually later with: php artisan migrate"
fi

# Create SQLite testing database if it doesn't exist
if [ ! -f database/testing.sqlite ]; then
    echo "📝 Creating SQLite testing database..."
    touch database/testing.sqlite
fi

echo ""
echo "✅ Setup complete! Your workspace is ready."
echo ""
echo "Next steps:"
echo "  1. Configure your .env file if needed"
echo "  2. Click the 'Run' button to start the Laravel server"
echo "  3. The API will be available at http://localhost:8000"
