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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUNTIME_SCRIPT="$ROOT_DIR/adminfront/scripts/runtime-mode.sh"

from_admin_url="$(
  APP_ENV=stage \
    ADMINFRONT_URL=https://sadmin.hmac.kr \
    sh "$RUNTIME_SCRIPT" --print-admin-public-url
)"

if [[ "$from_admin_url" != "https://sadmin.hmac.kr" ]]; then
  echo "ERROR: ADMINFRONT_URL was not exported as VITE_ADMIN_PUBLIC_URL" >&2
  exit 1
fi

from_callback="$(
  APP_ENV=stage \
    ADMINFRONT_CALLBACK_URLS=https://sadmin.hmac.kr/auth/callback \
    sh "$RUNTIME_SCRIPT" --print-admin-public-url
)"

if [[ "$from_callback" != "https://sadmin.hmac.kr" ]]; then
  echo "ERROR: ADMINFRONT_CALLBACK_URLS did not derive VITE_ADMIN_PUBLIC_URL" >&2
  exit 1
fi

explicit_value="$(
  APP_ENV=stage \
    ADMINFRONT_URL=https://wrong.example.test \
    VITE_ADMIN_PUBLIC_URL=https://sadmin.hmac.kr \
    sh "$RUNTIME_SCRIPT" --print-admin-public-url
)"

if [[ "$explicit_value" != "https://sadmin.hmac.kr" ]]; then
  echo "ERROR: explicit VITE_ADMIN_PUBLIC_URL should take precedence" >&2
  exit 1
fi

echo "OK: AdminFront public URL env policy is stable"
