#!/bin/bash
# ─────────────────────────────────────────────────────
# Musadaq Production Deployment Script
# Run this on the production server after syncing files
# ─────────────────────────────────────────────────────

set -e

echo "═══════════════════════════════════════════════"
echo "  مُصادَق — Production Deployment Script"
echo "═══════════════════════════════════════════════"

# 1. Install PHP dependencies
echo ""
echo "▶ Step 1: Installing Composer dependencies..."
cd /home/musadaq/htdocs/musadaq.intaleqapp.com
composer install --no-dev --optimize-autoloader

# 2. Ensure storage directories exist
echo ""
echo "▶ Step 2: Creating storage directories..."
mkdir -p storage/invoices
mkdir -p storage/logs
mkdir -p storage/exports
mkdir -p storage/temp
chmod -R 775 storage/

# 3. Set up the Cron Job for AI Queue Worker
echo ""
echo "▶ Step 3: Setting up Cron Job for AI Worker..."
echo ""
echo "  Run: crontab -e"
echo "  Add this line:"
echo ""
echo "  * * * * * /usr/bin/php /home/musadaq/htdocs/musadaq.intaleqapp.com/app/cron/process_batches.php >> /home/musadaq/htdocs/musadaq.intaleqapp.com/storage/logs/cron.log 2>&1"
echo ""
echo "  This runs the AI Queue Worker every minute."
echo "  The worker has its own lock file to prevent duplicates."
echo ""

# 4. Verify environment variables
echo "▶ Step 4: Checking .env configuration..."
if [ -f .env ]; then
    echo "  ✅ .env file found"
    
    # Check critical keys
    grep -q "GEMINI_API_KEY" .env && echo "  ✅ GEMINI_API_KEY set" || echo "  ❌ GEMINI_API_KEY missing!"
    grep -q "DB_HOST" .env && echo "  ✅ DB_HOST set" || echo "  ❌ DB_HOST missing!"
    grep -q "ENCRYPTION_KEY" .env && echo "  ✅ ENCRYPTION_KEY set" || echo "  ❌ ENCRYPTION_KEY missing!"
    grep -q "JWT_SECRET" .env && echo "  ✅ JWT_SECRET set" || echo "  ❌ JWT_SECRET missing!"
    grep -q "FCM_SERVER_KEY\|FIREBASE" .env && echo "  ✅ Firebase key set" || echo "  ⚠️  Firebase key missing (push notifications won't work)"
else
    echo "  ❌ .env file not found! Copy .env.example and configure it."
fi

echo ""
echo "═══════════════════════════════════════════════"
echo "  ✅ Deployment Complete!"
echo ""
echo "  Next steps:"
echo "  1. Add the Cron Job (shown above)"
echo "  2. Test the API: curl https://musadaq.intaleqapp.com/api/v1/auth/login"
echo "  3. Monitor logs: tail -f storage/logs/cron.log"
echo "═══════════════════════════════════════════════"
