#!/usr/bin/env bash
# deploy-backend-db-migrations.sh — Validate and run StarPost database
# migrations separately from postcard-design deployment.
#
# Usage:
#   cd /home/ubuntu/starpost-backend
#   bash scripts/deploy-backend-db-migrations.sh          # check only
#   bash scripts/deploy-backend-db-migrations.sh --apply  # confirm and run
#
# Optional:
#   MIGRATIONS="scripts/migrations/migrate-qr-artifacts.mjs scripts/migrations/migrate-tax-evidence.mjs"
#
# Notes:
#   - Migrations run sequentially.
#   - The backend is not restarted automatically because these migrations are
#     designed to be backward-compatible schema/data backfills.
#   - Any PostgreSQL deprecation warning emitted inside a migration must be
#     fixed in that migration's JavaScript, not in this wrapper.

set -Eeuo pipefail

APPLY=0
ASSUME_YES=0
for argument in "$@"; do
  case "$argument" in
    --apply) APPLY=1 ;;
    --yes) ASSUME_YES=1 ;;
    -h|--help)
      echo "Usage: bash scripts/deploy-backend-db-migrations.sh [--apply [--yes]]"
      echo "Without --apply, migrations are validated but never executed."
      exit 0
      ;;
    *) echo "ERROR: Unknown argument: $argument" >&2; exit 2 ;;
  esac
done

if [[ "$ASSUME_YES" -eq 1 && "$APPLY" -ne 1 ]]; then
  echo "ERROR: --yes is valid only together with --apply" >&2
  exit 2
fi

START_TIME="$(date +%s)"

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[1;36m'
BOLD='\033[1m'
NC='\033[0m'

ok()      { printf "${GREEN}   ✓ %s${NC}\n" "$1"; }
warn()    { printf "${YELLOW}   ⚠ %s${NC}\n" "$1"; }
section() { printf "\n${CYAN}${BOLD}%s${NC}\n" "$1"; }
die()     { printf "${RED}ERROR: %s${NC}\n" "$1" >&2; exit 1; }

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
ENV_FILE="$PROJECT_DIR/.env"

command -v node >/dev/null 2>&1 || die "Node.js is required."
command -v flock >/dev/null 2>&1 || die "flock is required."

LOCK_FILE="/tmp/starpost-backend-migrations.lock"
exec 9>"$LOCK_FILE"
flock -n 9 || die "Another backend migration process is already running."

DEFAULT_MIGRATIONS=(
  scripts/migrations/migrate-qr-artifacts.mjs
  scripts/migrations/migrate-tax-evidence.mjs
  scripts/migrations/migrate-business-analytics.mjs
)

if [[ -n "${MIGRATIONS:-}" ]]; then
  # shellcheck disable=SC2206
  MIGRATION_LIST=($MIGRATIONS)
else
  MIGRATION_LIST=("${DEFAULT_MIGRATIONS[@]}")
fi

printf "${CYAN}${BOLD}"
echo "╔══════════════════════════════════════════════════════╗"
echo "║  Star Post — Backend Operational Migrations         ║"
echo "╚══════════════════════════════════════════════════════╝"
printf "${NC}"
echo
printf "  Project: %s\n" "$PROJECT_DIR"
printf "  Env file: %s\n" "$ENV_FILE"

section "① Validating migration scripts"
for relative in "${MIGRATION_LIST[@]}"; do
  migration="$PROJECT_DIR/$relative"
  [[ -f "$migration" ]] || die "Missing migration: $relative"
  node --check "$migration"
  ok "$relative"
done

if [[ "$APPLY" -ne 1 ]]; then
  section "② Preflight complete — no migrations executed"
  warn "This command is check-only unless --apply is supplied."
  printf '  To apply intentionally: bash scripts/deploy-backend-db-migrations.sh --apply\n'
  exit 0
fi

if [[ "$ASSUME_YES" -ne 1 ]]; then
  [[ -t 0 ]] || die "Interactive confirmation is required; automation must explicitly use --apply --yes"
  printf "\n${YELLOW}${BOLD}This will modify the production database.${NC}\n"
  printf 'Type MIGRATE to continue: '
  read -r CONFIRMATION
  if [[ "$CONFIRMATION" != "MIGRATE" ]]; then
    warn "Migration cancelled; no migration was executed."
    exit 0
  fi
fi

run_migration() {
  local relative="$1"
  local migration="$PROJECT_DIR/$relative"

  section "Running $relative"

  if [[ -f "$ENV_FILE" ]]; then
    node --env-file="$ENV_FILE" "$migration"
  else
    node "$migration"
  fi

  ok "$relative completed"
}

section "② Running migrations sequentially"
for relative in "${MIGRATION_LIST[@]}"; do
  run_migration "$relative"
done

END_TIME="$(date +%s)"

echo
printf "${GREEN}${BOLD}"
echo "╔══════════════════════════════════════════════════════╗"
echo "║  ✓ Backend migrations completed successfully        ║"
echo "╚══════════════════════════════════════════════════════╝"
printf "${NC}"
echo
printf "  Migrations run: %s\n" "${#MIGRATION_LIST[@]}"
printf "  Duration:       %ss\n" "$((END_TIME - START_TIME))"
