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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUTPUT_FILE="$ROOT_DIR/config/.generated/auth-config.env"

bash "$ROOT_DIR/scripts/auth_config.sh" build >/tmp/baron-auth-config-orgfront-test.log

orgfront_callbacks="$(grep -E '^ORGFRONT_CALLBACK_URLS=' "$OUTPUT_FILE" | cut -d= -f2- || true)"
if [[ -z "$orgfront_callbacks" ]]; then
  echo "ERROR: generated auth config must include ORGFRONT_CALLBACK_URLS." >&2
  exit 1
fi

first_orgfront_callback="${orgfront_callbacks%%,*}"
if [[ -z "$first_orgfront_callback" ]]; then
  echo "ERROR: generated ORGFRONT_CALLBACK_URLS must not be empty." >&2
  exit 1
fi

allowed_returns="$(grep -E '^KRATOS_ALLOWED_RETURN_URLS_JSON=' "$OUTPUT_FILE" | cut -d= -f2- || true)"
if ! grep -Fq "$first_orgfront_callback" <<<"$allowed_returns"; then
  echo "ERROR: KRATOS_ALLOWED_RETURN_URLS_JSON must include orgfront callback: $first_orgfront_callback" >&2
  exit 1
fi

echo "OK: auth config includes OrgFront callback URLs"
