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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

assert_contains() {
  local file="$1"
  local pattern="$2"
  if ! grep -Fq -- "$pattern" "$file"; then
    echo "ERROR: missing pattern in $file: $pattern" >&2
    exit 1
  fi
}

assert_public_url() {
  local app_dir="$1"
  local app_url_env="$2"
  local callback_env="$3"
  local vite_public_env="$4"
  local expected_url="$5"

  local runtime_script="$ROOT_DIR/$app_dir/scripts/runtime-mode.sh"
  assert_contains "$runtime_script" "--print-public-url"

  local from_app_url
  from_app_url="$(
    env APP_ENV=stage \
      "$app_url_env=$expected_url" \
      sh "$runtime_script" --print-public-url
  )"
  if [[ "$from_app_url" != "$expected_url" ]]; then
    echo "ERROR: $app_url_env was not exported as $vite_public_env for $app_dir" >&2
    exit 1
  fi

  local from_callback
  from_callback="$(
    env APP_ENV=stage \
      "$callback_env=$expected_url/auth/callback" \
      sh "$runtime_script" --print-public-url
  )"
  if [[ "$from_callback" != "$expected_url" ]]; then
    echo "ERROR: $callback_env did not derive $vite_public_env for $app_dir" >&2
    exit 1
  fi

  local explicit_value
  explicit_value="$(
    env APP_ENV=stage \
      "$app_url_env=https://wrong.example.test" \
      "$vite_public_env=$expected_url" \
      sh "$runtime_script" --print-public-url
  )"
  if [[ "$explicit_value" != "$expected_url" ]]; then
    echo "ERROR: explicit $vite_public_env should take precedence for $app_dir" >&2
    exit 1
  fi
}

assert_contains "$ROOT_DIR/devfront/src/lib/authConfig.ts" "DEVFRONT_AUTH_CALLBACK_PATH"
assert_contains "$ROOT_DIR/devfront/src/app/routes.tsx" "DEVFRONT_AUTH_CALLBACK_PATH"
assert_contains "$ROOT_DIR/devfront/src/lib/auth.ts" "VITE_DEVFRONT_PUBLIC_URL"
assert_public_url \
  "devfront" \
  "DEVFRONT_URL" \
  "DEVFRONT_CALLBACK_URLS" \
  "VITE_DEVFRONT_PUBLIC_URL" \
  "https://sdev.hmac.kr"

assert_contains "$ROOT_DIR/orgfront/src/lib/authConfig.ts" "ORGFRONT_AUTH_CALLBACK_PATH"
assert_contains "$ROOT_DIR/orgfront/src/app/routes.tsx" "ORGFRONT_AUTH_CALLBACK_PATH"
assert_contains "$ROOT_DIR/orgfront/src/lib/auth.ts" "VITE_ORGFRONT_PUBLIC_URL"
assert_public_url \
  "orgfront" \
  "ORGFRONT_URL" \
  "ORGFRONT_CALLBACK_URLS" \
  "VITE_ORGFRONT_PUBLIC_URL" \
  "https://sorg.hmac.kr"

echo "OK: DevFront/OrgFront callback public URL policy is stable"
