/**
 * Two CORS policies, mounted per-router — never one global cors() call
 * (PLANNING.md §10).
 *
 *                     public router          admin router
 *   origins           PUBLIC_ORIGINS         ADMIN_ORIGINS
 *   Allow-Credentials  false                  true   (refresh cookie)
 *   methods            GET,POST,OPTIONS       GET,POST,PATCH,DELETE,OPTIONS
 *   Max-Age            86400                  86400
 *
 * They cannot be merged: a policy that sets Allow-Credentials while echoing the
 * public allowlist widens the credentialed surface for nothing. Unknown origins
 * get no Access-Control-Allow-Origin header at all (callback(null, false)) — not
 * an error, just an un-annotated response the browser then blocks.
 */
import cors, { type CorsOptions } from 'cors';
import { env } from '../env';

type OriginCallback = (err: Error | null, allow?: boolean) => void;

function originChecker(allowlist: readonly string[]) {
  return (origin: string | undefined, callback: OriginCallback): void => {
    // Non-browser clients (curl, server-to-server, same-origin) send no Origin.
    if (!origin) {
      callback(null, true);
      return;
    }
    callback(null, allowlist.includes(origin));
  };
}

const publicOptions: CorsOptions = {
  origin: originChecker(env.PUBLIC_ORIGINS),
  credentials: false,
  methods: ['GET', 'POST', 'OPTIONS'],
  maxAge: 86400,
};

const adminOptions: CorsOptions = {
  origin: originChecker(env.ADMIN_ORIGINS),
  credentials: true,
  methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
  maxAge: 86400,
};

export const publicCors = cors(publicOptions);
export const adminCors = cors(adminOptions);
