/**
 * Returns the canonical public base URL of this app.
 *
 * Source: `NEXTAUTH_URL` environment variable (required in production).
 *
 * - Production (`NODE_ENV=production`): throws if the variable is missing or empty,
 *   because email links would silently point at localhost otherwise.
 * - Development / test: falls back to `http://localhost:3100` and logs a one-time warning.
 *
 * Trailing slashes are stripped so callers can safely append paths with a leading `/`.
 */

let warned = false;

export function getAppBaseUrl(): string {
  const raw = process.env["NEXTAUTH_URL"]?.trim();

  if (raw) {
    return raw.replace(/\/$/, "");
  }

  if (process.env["NODE_ENV"] === "production") {
    throw new Error(
      "NEXTAUTH_URL must be set in production — email links will contain localhost otherwise. " +
      "Set it to the public URL of this app (e.g. https://capakraken.example.com).",
    );
  }

  if (!warned) {
    warned = true;
    console.warn(
      "[capakraken] NEXTAUTH_URL is not set — falling back to http://localhost:3100 for email links. " +
      "Set NEXTAUTH_URL in your .env to suppress this warning.",
    );
  }

  return "http://localhost:3100";
}
