#!/bin/bash
set -e

echo "=== NumoniX Backend Deployment Script ==="

# 1. Ensure storage and bootstrap/cache permissions
echo "--> Setting permissions..."
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

# 2. Check for .env
if [ ! -f .env ]; then
    if [ -f .env.production ]; then
        echo "--> Copying .env.production to .env..."
        cp .env.production .env
    else
        echo "--> Copying .env.example to .env..."
        cp .env.example .env
    fi
fi

# 3. Create storage directories if missing
echo "--> Creating storage subdirectories..."
mkdir -p storage/app/public
mkdir -p storage/app/private
mkdir -p storage/framework/cache/data
mkdir -p storage/framework/sessions
mkdir -p storage/framework/views
mkdir -p storage/logs

# 4. Storage symlink
echo "--> Creating storage symlink..."
php artisan storage:link || true

# 5. Run Database Migrations
echo "--> Running database migrations..."
php artisan migrate --force

# 6. Optimize and Cache for Production
echo "--> Clearing old cache & optimizing application..."
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

echo "=== Deployment Completed Successfully! ==="
echo "Next steps:"
echo "1. Log in to the Admin Dashboard at https://api.numonix.app/admin"
echo "2. Navigate to Settings -> Firebase Settings to upload your Firebase Service Account JSON"
echo "3. Ensure your Cron job is active: * * * * * cd $(pwd) && php artisan schedule:run >> /dev/null 2>&1"
echo "4. Ensure your queue worker or supervisor process is running: php artisan queue:work --sleep=3 --tries=3"