#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

fail=0
require_file() {
  if [[ ! -s "$1" ]]; then echo "MISSING: $1"; fail=1; else echo "OK: $1"; fi
}
require_file composer.lock
require_file .env
require_file vendor/autoload.php
require_file public/index.php

if [[ -f .env ]]; then
  grep -q '^APP_KEY=base64:' .env || { echo "ERROR: APP_KEY must be set."; fail=1; }
  grep -q '^APP_DEBUG=false' .env || { echo "ERROR: APP_DEBUG must be false."; fail=1; }
fi

if ! php -m | grep -qi '^pdo_mysql$'; then
  echo "ERROR: pdo_mysql PHP extension is missing."; fail=1
fi
if ! command -v composer >/dev/null 2>&1; then
  echo "ERROR: Composer is missing."; fail=1
fi

if [[ "$fail" -ne 0 ]]; then
  echo "Staging preflight FAILED."
  exit 1
fi

composer validate --strict
composer audit --no-interaction
php artisan about
php artisan route:list --except-vendor
echo "Staging preflight checks completed. Database migration and functional tests must still be run."
