/*
 * Which Laravel CMS the admin panel (and `npm run laravel`) talks to. One
 * flag, CMS_ENV, picks the API:
 *
 *   CMS_ENV=prod   https://api.secondlinenumber.com/api      (production)
 *   CMS_ENV=dev    https://secondphonenumber.worksqr.com/api (staging; the default)
 *
 * Settings that differ between the two servers (the CLI's admin token, the
 * Blog API key) can be set once per server with a _PROD or _DEV suffix, e.g.
 * LARAVEL_ADMIN_TOKEN_PROD; the plain name is the fallback. LARAVEL_API_URL,
 * when set, overrides the API the flag picks.
 *
 * No imports: next.config.ts and the scripts read this too.
 */

export const laravelApis = {
  prod: "https://api.secondlinenumber.com/api",
  dev: "https://secondphonenumber.worksqr.com/api",
} as const;

export type CmsTarget = keyof typeof laravelApis;

type Env = Record<string, string | undefined>;

/** The server CMS_ENV names; dev when unset. Throws on an unknown value, so a typo can't silently pick a server. */
export function cmsTarget(env: Env = process.env): CmsTarget {
  const value = env.CMS_ENV?.trim().toLowerCase();
  if (
    !value ||
    value === "dev" ||
    value === "development" ||
    value === "staging"
  )
    return "dev";
  if (value === "prod" || value === "production") return "prod";
  throw new Error(`CMS_ENV must be "prod" or "dev", not "${env.CMS_ENV}".`);
}

/** A setting for the selected server: NAME_PROD / NAME_DEV first, then NAME. */
export function cmsSetting(name: string, env: Env = process.env) {
  const specific = env[`${name}_${cmsTarget(env).toUpperCase()}`]?.trim();
  return specific || env[name]?.trim() || undefined;
}

/** The Laravel API base URL (no trailing slash): LARAVEL_API_URL, else the CMS_ENV API. */
export function laravelApiUrl(env: Env = process.env) {
  return (
    cmsSetting("LARAVEL_API_URL", env) || laravelApis[cmsTarget(env)]
  ).replace(/\/+$/, "");
}
