/**
 * Public configuration, resolved at request time on the server.
 *
 * None of these values are secret — a Turnstile site key and an OAuth client id are both
 * printed into the page by design. What matters is *when* they are read.
 *
 * Next.js replaces `process.env.NEXT_PUBLIC_*` with a literal at build time, in the server
 * bundle as well as the client one. The production web image is built by `docker build`,
 * which has none of these set, so every `NEXT_PUBLIC_` read compiles down to `undefined`
 * and the `environment:` block in docker-compose.prod.yml never gets a say. The failure is
 * invisible in development — `next dev` reads the environment on each request, so it all
 * works locally — and total in production: the Turnstile widget renders with no site key,
 * never produces a token, and the server-side check refuses every open registration.
 *
 * So the web container is given un-prefixed names, which Next leaves as genuine runtime
 * lookups, and these accessors run server-side only. The values reach client components as
 * props. `eslint.config.mjs` bans `process.env.NEXT_PUBLIC_*` outright so the shortcut
 * cannot creep back in.
 */
import "server-only";

/** What `.env.example` ships before the real accounts exist (task 1.10). */
const PLACEHOLDER_PREFIXES = ["your-", "changeme"];

function configured(raw: string | undefined): string | null {
  const value = raw?.trim();
  if (!value) return null;
  if (PLACEHOLDER_PREFIXES.some((p) => value.toLowerCase().startsWith(p))) return null;
  return value;
}

/**
 * Cloudflare's `1x0000…` test key is a real, working site key that always passes, so it is
 * returned like any other. It pairs with the matching test secret on the API side, which
 * short-circuits verification — that is what makes the open-link flow exercisable locally
 * without a Cloudflare account.
 */
export function turnstileSiteKey(): string | null {
  return configured(process.env.TURNSTILE_SITE_KEY);
}

export function googleClientId(): string | null {
  return configured(process.env.GOOGLE_CLIENT_ID);
}

/**
 * Where this deployment is reachable, for `metadataBase` (design D7).
 *
 * Deliberately no fallback to the request's own origin, because the fallback would be
 * redundant: every preview URL arrives from the API already absolute, and `metadataBase`
 * only ever resolves relative ones. Reading `headers()` would also foreclose prerendering
 * `/e/[slug]`, which that route's own comment contemplates for the Phase 6 load test.
 *
 * When this is unset, `metadataBase` is omitted rather than guessed.
 */
export function appBaseUrl(): string | null {
  return configured(process.env.APP_BASE_URL);
}

/**
 * Only renders the development sign-in box. The API refuses that route unless
 * `AUTH_DEV_BYPASS` is set there too, so this flag alone cannot let anyone in.
 */
export function authDevBypassEnabled(): boolean {
  return process.env.AUTH_DEV_BYPASS === "true";
}
