#!/usr/bin/env bash
#
# verify_migrations.sh — Confirm the CRM upgrade migrations are applied.
#
# Runs `php artisan migrate:status` and reports the Ran/Pending state of each
# new CRM migration. Run this from the backend/ directory (or its parent).
#
# USAGE
#   ./scripts/verify_migrations.sh
#
# EXIT CODE
#   0  all listed CRM migrations are applied (Ran)
#   1  one or more are pending/missing, or artisan failed

set -u

# Resolve backend root: prefer CWD if artisan is here, else parent of scripts/.
if [ -f "./artisan" ]; then
  ROOT="."
elif [ -f "$(dirname "$0")/../artisan" ]; then
  ROOT="$(dirname "$0")/.."
else
  echo "ERROR: could not find Laravel 'artisan'. Run from backend/." >&2
  exit 1
fi

# New CRM migrations introduced by the Sprint 1-7 upgrade.
CRM_MIGRATIONS="
2026_08_10_000001_create_crm_lead_categories_table
2026_08_10_000002_alter_crm_leads_sprint1
2026_08_11_000001_alter_crm_lead_proposals_sprint2
2026_08_11_000002_create_crm_proposal_items_table
2026_08_11_000003_alter_fin_receivables_add_lead_id
2026_08_12_000001_create_crm_lead_contacts_table
2026_08_12_000002_alter_fin_parties_crm_enrichment
2026_08_13_000001_alter_crm_tender_details_sprint4
2026_08_13_000002_alter_crm_leads_add_project_id
2026_08_14_000001_create_audit_logs_table
"

echo "Running: php artisan migrate:status"
echo "------------------------------------------------------------"
STATUS="$(php "$ROOT/artisan" migrate:status 2>&1)"
RC=$?
if [ $RC -ne 0 ]; then
  echo "ERROR: php artisan migrate:status failed:" >&2
  printf '%s\n' "$STATUS" >&2
  exit 1
fi

MISSING=0
for m in $CRM_MIGRATIONS; do
  line="$(printf '%s\n' "$STATUS" | grep -F "$m")"
  if [ -z "$line" ]; then
    printf '  [MISSING] %s\n' "$m"
    MISSING=$((MISSING + 1))
  elif printf '%s' "$line" | grep -qiE 'ran|\[[0-9]+\]|Yes'; then
    printf '  [ RAN   ] %s\n' "$m"
  else
    printf '  [PENDING] %s\n' "$m"
    MISSING=$((MISSING + 1))
  fi
done

echo "------------------------------------------------------------"
if [ "$MISSING" -gt 0 ]; then
  echo "RESULT: $MISSING CRM migration(s) not applied. Run: php artisan migrate"
  exit 1
fi
echo "RESULT: all CRM upgrade migrations are applied."
exit 0
