/**
 * CORS middleware for cross-origin requests from the website.
 *
 * Validates the request Origin header against the allowed origin
 * before setting CORS response headers.
 */

import type { Context, Next } from "hono";

export function corsHeaders(origin: string): Record<string, string> {
  return {
    "Access-Control-Allow-Origin": origin,
    "Access-Control-Allow-Methods": "POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Stripe-Signature",
    "Access-Control-Max-Age": "86400",
  };
}

export function corsMiddleware(allowedOrigin: string) {
  return async (c: Context, next: Next) => {
    const requestOrigin = c.req.header("Origin");

    // Stripe webhooks don't send Origin headers — allow them through
    // All other cross-origin requests must match the allowed origin
    if (requestOrigin && requestOrigin !== allowedOrigin) {
      return new Response("Forbidden", { status: 403 });
    }

    // Handle preflight
    if (c.req.method === "OPTIONS") {
      return new Response(null, {
        status: 204,
        headers: corsHeaders(allowedOrigin),
      });
    }

    await next();

    // Add CORS headers to all responses
    const headers = corsHeaders(allowedOrigin);
    for (const [key, value] of Object.entries(headers)) {
      c.res.headers.set(key, value);
    }
  };
}
