#!/usr/bin/env bash
set -euo pipefail

# Run once on the server after uploading the project files.
# Usage: bash deploy/server-setup.sh

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

if [[ ! -f .env ]]; then
    if [[ -f .env.production.example ]]; then
        cp .env.production.example .env
        echo "Created .env from .env.production.example — edit it before continuing."
        exit 1
    fi

    echo "Missing .env file. Copy .env.production.example to .env and configure it."
    exit 1
fi

if ! grep -q '^APP_KEY=base64:' .env 2>/dev/null; then
    php artisan key:generate --force
fi

php artisan migrate --force
php artisan db:seed --force
php artisan storage:link --force 2>/dev/null || true
php artisan optimize

chmod -R ug+rwx storage bootstrap/cache 2>/dev/null || true

if [[ ! -f .htaccess ]] && [[ -f deploy/htaccess.subdirectory ]]; then
    cp deploy/htaccess.subdirectory .htaccess
    echo "Installed .htaccess for subdirectory hosting (routes to public/)."
fi

if [[ ! -f public/build/manifest.json ]]; then
    echo ""
    echo "WARNING: public/build/manifest.json is missing."
    echo "Run npm run build locally (with VITE_APP_BASE set for subdirectory deploy) and upload public/build."
fi

echo ""
echo "Deployment setup complete."
echo "1. APP_URL in .env must match your URL (e.g. https://proficientpoint.com/azin)"
echo "2. public/build must exist on the server (run npm run build before upload)"
echo "3. Visit your site/setup/master-admin to create the first admin (only when no users exist)."
echo "4. Run a queue worker if you use queued jobs: php artisan queue:work --daemon"
