#!/bin/sh
set -eu

# Apply this worker's D1 migrations. Run from a worker directory (e.g. via
# `bun turbo -F rooms migrate`). Defaults to --remote; pass --local to target the
# dev SQLite db. Extra args pass through to `wrangler d1 migrations apply`.
#
# Remote/preview migrations need the real database id, but the committed
# wrangler.jsonc carries a "local" placeholder. This splices the id from
# RECFLARE_D1 (gitignored .env / CI secrets) into a generated config alongside the
# original — exactly like run-wrangler-deploy — so relative paths (migrations_dir)
# still resolve. Local migrations use the placeholder directly and need no id.

if ! grep -q '"database_id": *"local"' wrangler.jsonc 2>/dev/null; then
	echo "error: this worker has no D1 database to migrate (no \"local\" placeholder in wrangler.jsonc)" >&2
	exit 1
fi

# Target the database by its name from the committed config.
DB_NAME=$(grep '"database_name"' wrangler.jsonc | head -1 |
	sed -E 's/.*"database_name": *"([^"]*)".*/\1/')

# Detect a caller-supplied target flag; default to --remote when none is given.
LOCAL=0
HAS_TARGET=0
for arg in "$@"; do
	case "$arg" in
	--local) LOCAL=1 HAS_TARGET=1 ;;
	--remote | --preview) HAS_TARGET=1 ;;
	esac
done

# wrangler's "your database may be unavailable during the migration, continue?"
# confirmation can't be answered when this runs under turbo (it doesn't forward
# stdin to the task), so run non-interactively — wrangler skips the prompt and
# proceeds, still capturing a backup. An already-set CI value (real CI) wins.
export CI=${CI:-true}

if [ "$LOCAL" -eq 1 ]; then
	# Local db keys off the "local" placeholder, so the committed config is fine.
	exec wrangler d1 migrations apply "$DB_NAME" "$@"
fi

# Load RECFLARE_D1 from the gitignored root .env if not already set (mirrors
# run-wrangler-deploy's handling of RECFLARE_DOMAIN). An already-set value wins.
if [ -z "${RECFLARE_D1:-}" ]; then
	ENV_FILE="$(git rev-parse --show-toplevel)/.env"
	if [ -f "$ENV_FILE" ]; then
		set -a
		. "$ENV_FILE"
		set +a
	fi
fi

DB_ID=${RECFLARE_D1:-}
if [ -z "$DB_ID" ]; then
	echo "error: RECFLARE_D1 is not set — add the recflare D1 id to .env (see .env.example)" >&2
	exit 1
fi

# Generated alongside the original so its relative paths still resolve. Gitignored;
# removed on exit so `wrangler dev` is unaffected.
trap 'rm -f wrangler.generated.jsonc' EXIT
sed -E 's/("database_id"[[:space:]]*:[[:space:]]*")[^"]*(")/\1'"$DB_ID"'\2/' \
	wrangler.jsonc >wrangler.generated.jsonc

# Default to --remote when the caller passed no target flag.
[ "$HAS_TARGET" -eq 1 ] || set -- "$@" --remote

wrangler d1 migrations apply "$DB_NAME" --config wrangler.generated.jsonc "$@"
