#!/usr/bin/env bash
# =============================================================================
# Local staging rehearsal helper (Linux/macOS/Git Bash)
# Usage:
#   ./scripts/run-local-staging-rehearsal.sh USER PASSWORD BACKUP_SQL_PATH
# =============================================================================

set -euo pipefail

if [ "$#" -lt 3 ]; then
  echo "Usage: $0 USER PASSWORD BACKUP_SQL_PATH"
  exit 1
fi

MYSQL_USER="$1"
MYSQL_PASS="$2"
BACKUP_SQL="$3"
DB_NAME="team_management_staging"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" -e \
  "DROP DATABASE IF EXISTS \`$DB_NAME\`; CREATE DATABASE \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"

mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" "$DB_NAME" < "$BACKUP_SQL"

for file in 00-preflight-checks 01-baseline-migrations 02-access-control-schema 03-member-access-role; do
  echo "Running $file.sql..."
  mysql -u "$MYSQL_USER" -p"$MYSQL_PASS" "$DB_NAME" < "$SCRIPT_DIR/sql/$file.sql"
done

echo ""
echo "Schema steps 00-03 complete."
echo "Next:"
echo "  DATABASE_URL=mysql://$MYSQL_USER:$MYSQL_PASS@localhost:3306/$DB_NAME npm run seed:access-roles"
echo "  mysql -u $MYSQL_USER -p$MYSQL_PASS $DB_NAME < $SCRIPT_DIR/sql/04-backfill-member-roles.sql"
echo "  mysql -u $MYSQL_USER -p$MYSQL_PASS $DB_NAME < $SCRIPT_DIR/sql/05-permission-scope-updates.sql"
echo "  mysql -u $MYSQL_USER -p$MYSQL_PASS $DB_NAME < $SCRIPT_DIR/sql/06-post-migration-verify.sql"
