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

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

if [[ ! -f ".env" ]]; then
  echo "ERROR: .env is missing in $ROOT_DIR"
  exit 1
fi

echo "== LineUp France cPanel preflight =="
echo "Root: $ROOT_DIR"

echo
echo "-- PHP version --"
php -v | head -n 1

echo
echo "-- Composer version --"
composer --version

echo
echo "-- Laravel about --"
php artisan about

echo
echo "-- Migration status --"
MIGRATE_STATUS_OUTPUT="$(php artisan migrate:status --no-interaction)"
echo "$MIGRATE_STATUS_OUTPUT"

if echo "$MIGRATE_STATUS_OUTPUT" | grep -q "Pending"; then
  echo
  echo "ERROR: Pending migrations detected."
  echo "Run: php artisan migrate --force"
  exit 2
fi

echo
echo "-- BO routes check --"
ROUTES_OUTPUT="$(php artisan route:list)"
for required in "bo/dashboard" "bo/finance" "bo/users" "bo/missions" "bo/kyc" "bo/payouts"; do
  if ! echo "$ROUTES_OUTPUT" | grep -q "$required"; then
    echo "ERROR: Missing BO route containing '$required'"
    exit 4
  fi
done
if ! echo "$ROUTES_OUTPUT" | grep -q "reset-password/{token}"; then
  echo "ERROR: Missing password reset route '/reset-password/{token}'"
  exit 4
fi
echo "OK: required BO routes found"

echo
echo "-- REST verbs guard (PATCH/DELETE) --"
for file in ".htaccess" "public/.htaccess"; do
  if [[ ! -f "$file" ]]; then
    echo "ERROR: missing $file"
    exit 7
  fi

  if ! grep -Eq "AllowMethods.+PATCH.+DELETE|AllowMethods.+DELETE.+PATCH" "$file"; then
    echo "ERROR: $file does not declare AllowMethods with PATCH/DELETE."
    echo "Expected: AllowMethods reset GET POST PUT PATCH DELETE OPTIONS HEAD"
    exit 7
  fi
done
echo "OK: PATCH/DELETE guard configured in .htaccess files"

echo
echo "-- Writable dirs check --"
RUNTIME_DIRS=(
  storage
  bootstrap/cache
  storage/logs
  storage/framework/cache
  storage/framework/sessions
  storage/framework/views
)
for dir in "${RUNTIME_DIRS[@]}"; do
  if [[ ! -d "$dir" ]]; then
    mkdir -p "$dir" || {
      echo "ERROR: unable to create runtime dir $dir"
      exit 3
    }
  fi

  if [[ ! -w "$dir" ]]; then
    echo "ERROR: $dir is not writable"
    exit 3
  fi

  echo "OK: $dir writable"
done

TMP_DIR="${TMPDIR:-/tmp}"
if [[ ! -w "$TMP_DIR" ]]; then
  echo "ERROR: temp dir $TMP_DIR is not writable (tempnam will fail)."
  exit 3
fi
echo "OK: temp dir writable ($TMP_DIR)"

echo
echo "-- Env sanity checks --"
env_value() {
  local key="$1"
  local value
  value="$(grep -E "^${key}=" .env | tail -n 1 | cut -d= -f2- || true)"
  value="${value%\"}"
  value="${value#\"}"
  printf "%s" "$value"
}

env_occurrences() {
  local key="$1"
  grep -cE "^${key}=" .env || true
}

APP_ENV_VALUE="$(env_value APP_ENV)"
PAYMENTS_SIMULATE="$(env_value LINEUP_PAYMENTS_SIMULATE)"
MAIL_MAILER_VALUE="$(env_value MAIL_MAILER)"

DUPLICATE_KEYS=(
  APP_ENV
  APP_DEBUG
  APP_URL
  MAIL_MAILER
  MAIL_HOST
  MAIL_USERNAME
  MAIL_PASSWORD
  FIREBASE_PROJECT
  PAYPAL_MODE
  LINEUP_PAYMENTS_SIMULATE
)
DUPLICATE_COUNT=0
for key in "${DUPLICATE_KEYS[@]}"; do
  occurrences="$(env_occurrences "$key")"
  if [[ "${occurrences:-0}" -gt 1 ]]; then
    echo "WARN: duplicate key '$key' found $occurrences times in .env"
    DUPLICATE_COUNT=$((DUPLICATE_COUNT + 1))
  fi
done

if [[ "$APP_ENV_VALUE" == "production" ]]; then
  if [[ "$DUPLICATE_COUNT" -gt 0 ]]; then
    echo "ERROR: duplicate env keys detected in production .env."
    echo "Keep one value per key to avoid silent misconfiguration."
    exit 6
  fi

  APP_URL_VALUE="$(env_value APP_URL)"
  MAIL_HOST_VALUE="$(env_value MAIL_HOST)"
  MAIL_USERNAME_VALUE="$(env_value MAIL_USERNAME)"
  MAIL_PASSWORD_VALUE="$(env_value MAIL_PASSWORD)"
  FIREBASE_PROJECT_VALUE="$(env_value FIREBASE_PROJECT)"
  FIREBASE_CREDENTIALS_VALUE="$(env_value FIREBASE_CREDENTIALS)"

  if [[ -z "$APP_URL_VALUE" || "$APP_URL_VALUE" == *"localhost"* ]]; then
    echo "ERROR: APP_URL must be a real production URL."
    exit 5
  fi

  if [[ "$MAIL_MAILER_VALUE" == "log" || -z "$MAIL_HOST_VALUE" || -z "$MAIL_USERNAME_VALUE" || -z "$MAIL_PASSWORD_VALUE" ]]; then
    echo "ERROR: SMTP mail is not fully configured for production."
    exit 5
  fi

  if [[ -z "$FIREBASE_PROJECT_VALUE" ]]; then
    echo "ERROR: FIREBASE_PROJECT is missing in production."
    exit 5
  fi

  if [[ -n "$FIREBASE_CREDENTIALS_VALUE" && ! -f "$FIREBASE_CREDENTIALS_VALUE" ]]; then
    echo "ERROR: FIREBASE_CREDENTIALS file not found at '$FIREBASE_CREDENTIALS_VALUE'."
    echo "Upload your Firebase service account JSON to this path."
    exit 5
  fi

  if [[ -L "public/storage" ]]; then
    :
  elif [[ -d "public/storage" ]]; then
    echo "WARN: public/storage is a directory (not a symlink)."
    echo "This works but symlink is recommended: php artisan storage:link"
  else
    echo "ERROR: public/storage symlink/directory is missing in production."
    echo "Run: php artisan storage:link"
    exit 5
  fi

  if [[ "$PAYMENTS_SIMULATE" == "false" ]]; then
    STRIPE_SECRET_KEY_VALUE="$(env_value LINEUP_STRIPE_SECRET_KEY)"
    STRIPE_WEBHOOK_SECRET_VALUE="$(env_value LINEUP_STRIPE_WEBHOOK_SECRET)"
    PAYPAL_CLIENT_ID_VALUE="$(env_value LINEUP_PAYPAL_CLIENT_ID)"
    PAYPAL_CLIENT_SECRET_VALUE="$(env_value LINEUP_PAYPAL_CLIENT_SECRET)"

    if [[ -z "$PAYPAL_CLIENT_ID_VALUE" ]]; then
      PAYPAL_CLIENT_ID_VALUE="$(env_value PAYPAL_CLIENT_ID)"
    fi
    if [[ -z "$PAYPAL_CLIENT_SECRET_VALUE" ]]; then
      PAYPAL_CLIENT_SECRET_VALUE="$(env_value PAYPAL_SECRET)"
    fi

    if [[ -z "$STRIPE_SECRET_KEY_VALUE" || -z "$STRIPE_WEBHOOK_SECRET_VALUE" ]]; then
      echo "ERROR: Stripe live credentials missing while LINEUP_PAYMENTS_SIMULATE=false."
      exit 5
    fi

    if [[ -z "$PAYPAL_CLIENT_ID_VALUE" || -z "$PAYPAL_CLIENT_SECRET_VALUE" ]]; then
      echo "ERROR: PayPal live credentials missing while LINEUP_PAYMENTS_SIMULATE=false."
      exit 5
    fi
  fi
elif [[ "$DUPLICATE_COUNT" -gt 0 ]]; then
  echo "WARN: duplicate env keys detected (non-production)."
fi

echo "OK: env sanity checks"

echo
echo "Preflight OK."
