#!/usr/bin/env bash
# Değişen database/migration_*.sql dosyalarında yıkıcı SQL pattern taraması.
# Kullanım: ./scripts/verify-migration-safety.sh [base_ref]
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BASE="${1:-origin/main}"

ALLOWLIST=(
  "migration_cleanup_demo_footer_menu.sql"
  "optional_remove_bootstrap_demo_content.sql"
)

is_allowlisted() {
  local base
  base="$(basename "$1")"
  local name
  for name in "${ALLOWLIST[@]}"; do
    if [[ "$base" == "$name" ]]; then
      return 0
    fi
  done
  return 1
}

FILES=()
if ! git -C "$ROOT" rev-parse --verify "$BASE" >/dev/null 2>&1; then
  echo "[migration-safety] base ref yok ($BASE); tum migration_*.sql taraniyor."
  while IFS= read -r -d '' f; do
    FILES+=("$f")
  done < <(find "$ROOT/database" -maxdepth 1 -name 'migration_*.sql' -type f -print0 2>/dev/null | sort -z)
else
  while IFS= read -r line; do
    [[ -n "$line" ]] && FILES+=("$ROOT/$line")
  done < <(git -C "$ROOT" diff --name-only "$BASE"...HEAD -- 'database/migration_*.sql' 2>/dev/null || true)
fi

if [[ ${#FILES[@]} -eq 0 ]]; then
  echo "[migration-safety] Degisen migration yok — OK"
  exit 0
fi

FAIL=0
for path in "${FILES[@]}"; do
  [[ -f "$path" ]] || continue
  if is_allowlisted "$path"; then
    echo "[migration-safety] allowlist: $(basename "$path")"
    continue
  fi
  name="$(basename "$path")"

  if grep -qiE '^[[:space:]]*drop[[:space:]]+table[[:space:]]+' "$path"; then
    if ! grep -qi 'drop table if exists' "$path"; then
      echo "[MIGRATION_DESTRUCTIVE] $name — DROP TABLE without IF EXISTS"
      FAIL=1
    fi
  fi
  if grep -qiE '^[[:space:]]*truncate[[:space:]]+' "$path"; then
    echo "[MIGRATION_DESTRUCTIVE] $name — TRUNCATE"
    FAIL=1
  fi
  if grep -qiE 'delete[[:space:]]+from[[:space:]]+[`a-zA-Z0-9_]+[[:space:]]*;' "$path"; then
    echo "[MIGRATION_DESTRUCTIVE] $name — DELETE FROM without WHERE"
    FAIL=1
  fi
  if grep -qiE 'drop[[:space:]]+column' "$path" && ! grep -qi 'information_schema' "$path"; then
    echo "[MIGRATION_DESTRUCTIVE] $name — DROP COLUMN without information_schema guard"
    FAIL=1
  fi
done

if [[ "$FAIL" -ne 0 ]]; then
  echo ""
  echo "Bkz. docs/production-gates.md — Migration safety"
  exit 1
fi

echo "[migration-safety] OK (${#FILES[@]} dosya)"
exit 0
