/**
 * Canonical home for rate-limiting and anon session-id minting.
 *
 * Today: mints `multideal_anon_sid` HttpOnly cookie on first non-WebSocket GET
 * so downstream push/notification logic can correlate anonymous visitors.
 *
 * Per-route rate-limiting continues to live in
 * `src/server/auth/rate-limit-check.ts` (scopes defined in
 * `src/server/auth/rate-limit-policies.ts`).
 */
import type { MiddlewareHandler } from 'astro';

const COOKIE_NAME = 'multideal_anon_sid';
const MAX_AGE_S = 60 * 60 * 24 * 30; // 30 days

function hasCookie(req: Request, name: string): boolean {
  const raw = req.headers.get('cookie');
  if (!raw) return false;
  return raw.split(/;\s*/).some((p) => p.startsWith(`${name}=`));
}

function makeCookie(value: string): string {
  return `${COOKIE_NAME}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${MAX_AGE_S}`;
}

export const rateLimitMiddleware: MiddlewareHandler = async (ctx, next) => {
  const isUpgrade = ctx.request.headers.get('upgrade')?.toLowerCase() === 'websocket';
  const res = await next();
  if (isUpgrade) return res;
  if (ctx.request.method !== 'GET') return res;
  if (hasCookie(ctx.request, COOKIE_NAME)) return res;
  const id = crypto.randomUUID();
  const headers = new Headers(res.headers);
  headers.append('set-cookie', makeCookie(id));
  return new Response(res.body, {
    status: res.status,
    statusText: res.statusText,
    headers,
  });
};
