/**
 * Request authentication for Forge's API surface (API-key / session).
 *
 * A request is authenticated if it carries a valid persistent API key — a
 * `forge_sk_`-prefixed key in Authorization: Bearer, the x-forge-token header,
 * or the forge-api-token cookie — OR a VALIDATED NextAuth browser session. The
 * session is checked with the framework decoder (auth()), NOT by cookie presence
 * — a forged or unsigned session-token cookie does not pass. The legacy
 * admin-minted in-memory token is NOT handled here; routes that accept it call
 * isValidToken() in addition. Centralizes the key+session check so those routes
 * share one implementation. (Named api-auth to avoid colliding with lib/auth.ts,
 * the NextAuth config.)
 *
 * Route handlers call isAuthenticated() for the combined key-or-session check.
 */

import { verifyApiKey } from './api-keys';
import { auth } from './auth';

/** Extract a bearer/token credential from the request, if any. */
export function extractToken(req: Request): string | null {
  const authz = req.headers.get('authorization');
  if (authz && /^Bearer\s+/i.test(authz)) return authz.replace(/^Bearer\s+/i, '').trim();
  const header = req.headers.get('x-forge-token');
  if (header) return header;
  const cookie = req.headers.get('cookie') || '';
  const m = cookie.match(/forge-api-token=([^;]+)/);
  return m ? m[1] : null;
}

/** True if the request carries a valid persistent API key — a `forge_sk_` key in
 *  Authorization: Bearer, x-forge-token, or the forge-api-token cookie. (The
 *  legacy admin-minted token is checked separately by isValidToken.) */
export function hasValidApiKey(req: Request): boolean {
  return verifyApiKey(extractToken(req));
}

/** True if there is a VALIDATED NextAuth browser session for the current request.
 *  Uses the framework decoder (auth()) — NOT cookie presence — so a forged or
 *  unsigned session-token cookie does not pass. Must be called within a request
 *  context (route handler / server component); returns false otherwise. */
export async function hasSession(): Promise<boolean> {
  try { return !!(await auth()); } catch { return false; }
}

/** True if the request presents a valid API key or a validated browser session. */
export async function isAuthenticated(req: Request): Promise<boolean> {
  if (hasValidApiKey(req)) return true;
  return hasSession();
}
