import { createHash, timingSafeEqual } from "node:crypto";

/**
 * Whether a request may run the scheduled jobs: the shared `CRON_SECRET`, as
 * Vercel's cron sends it (`Authorization: Bearer <secret>`).
 *
 * Both apps wrote this, the same way in substance. The union keeps each one's
 * better half:
 *
 * - **An unset secret refuses everything (503)** rather than running
 *   unauthenticated. Both.
 * - **Compared as SHA-256 digests with `timingSafeEqual`** (Quickie). Equal
 *   lengths whatever was sent, so the comparison is constant-time and leaks not
 *   even the secret's length. AltEd compared the raw bytes after a length check.
 * - **A committed development secret is refused in production** (Quickie). Next
 *   loads `.env` in production too, so a host that forgets its own value would
 *   otherwise run on the one in the repository.
 * - **No secret in the address unless asked for** (AltEd). `?secret=` lands in
 *   every request log on the way; a route only Vercel calls has no use for it.
 *   Quickie accepted it everywhere, AltEd on the tick. Off by default here.
 * - **The Bearer scheme is required.** Quickie's check stripped an optional
 *   prefix, so a bare secret in the header also passed.
 *
 * Returns a decision, not a `Response`: each app answers in its own envelope.
 */
export type CronAuthResult = { ok: true } | { ok: false; status: 401 | 503; message: string };

export interface CronAuthOptions {
  /** The secret. Default `process.env.CRON_SECRET`. */
  secret?: string;
  /** Accept `?secret=` from a scheduler that can only call an address. Default `false`. */
  allowQuery?: boolean;
  /** Values that are public — committed to the repository — and so refused in production. */
  publicSecrets?: readonly string[];
  /** Default `process.env.NODE_ENV === "production"`. */
  production?: boolean;
  /** What the refusal calls this endpoint: "Cron", "The harvest". Default "Cron". */
  label?: string;
}

const digest = (value: string) => createHash("sha256").update(value).digest();

export function checkCronRequest(request: Request, options: CronAuthOptions = {}): CronAuthResult {
  const label = options.label ?? "Cron";
  const secret = options.secret ?? process.env.CRON_SECRET ?? "";
  if (!secret) return { ok: false, status: 503, message: `${label} is not configured (CRON_SECRET unset).` };
  const production = options.production ?? process.env.NODE_ENV === "production";
  if (production && options.publicSecrets?.includes(secret)) {
    return { ok: false, status: 503, message: `${label} is not configured (CRON_SECRET is the development value).` };
  }

  const header = request.headers.get("authorization") ?? "";
  const bearer = /^Bearer\s+(.+)$/i.exec(header)?.[1];
  const provided =
    bearer ?? (options.allowQuery ? (new URL(request.url).searchParams.get("secret") ?? undefined) : undefined);
  if (!provided || !timingSafeEqual(digest(provided), digest(secret))) {
    return { ok: false, status: 401, message: "Unauthorized" };
  }
  return { ok: true };
}
