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

if [ $# -eq 0 ]; then
  echo "Usage: ./scripts/prisma-run-safe.sh <prisma-args...>"
  exit 1
fi

if [ -f .env.local ]; then
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ''|'#'*) continue ;;
    esac
    key=${line%%=*}
    value=${line#*=}
    if [ -z "${!key+x}" ]; then
      export "$key=$value"
    fi
  done < .env.local
fi

if [ -z "${DATABASE_URL:-}" ]; then
  echo "DATABASE_URL is not set."
  exit 1
fi

if [ "${CI:-}" != "true" ] && [ "${ALLOW_REMOTE_PRISMA_COMMANDS:-}" != "1" ]; then
  if ! printf '%s' "$DATABASE_URL" | grep -Eq '@(localhost|127\.0\.0\.1|postgres|ballbox-postgres)(:|/)|//(localhost|127\.0\.0\.1|postgres|ballbox-postgres)(:|/)'; then
    echo "Refused: Prisma command targets a non-local DATABASE_URL."
    echo "Use a local DB for normal dev/test flow."
    echo "If this is intentional, rerun with ALLOW_REMOTE_PRISMA_COMMANDS=1."
    exit 1
  fi
fi

exec pnpm exec prisma "$@"
