#!/usr/bin/env bash

set -euo pipefail

APP_DIR="/var/www/churchxtra"
PHP_BIN="/usr/bin/php"
COMPOSER_BIN="/usr/local/bin/composer"

echo "Starting ChurchXtra deployment..."

cd "$APP_DIR"

echo "Enabling maintenance mode..."
$PHP_BIN artisan down --retry=60 || true

echo "Installing production dependencies..."
$COMPOSER_BIN install \
    --no-dev \
    --prefer-dist \
    --no-interaction \
    --optimize-autoloader

echo "Running database migrations..."
$PHP_BIN artisan migrate --force

echo "Creating storage link..."
$PHP_BIN artisan storage:link || true

echo "Clearing old caches..."
$PHP_BIN artisan optimize:clear

echo "Caching production configuration..."
$PHP_BIN artisan config:cache
$PHP_BIN artisan route:cache
$PHP_BIN artisan view:cache

echo "Restarting queue workers..."
$PHP_BIN artisan queue:restart

echo "Running production readiness audit..."
$PHP_BIN artisan churchxtra:production-check --strict

echo "Disabling maintenance mode..."
$PHP_BIN artisan up

echo "ChurchXtra deployment completed successfully."