import { RouteContext, RouteHandler } from '@server/middleware/withErrorHandler';

export const WIDGET_CORS_HEADERS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
  'Access-Control-Max-Age': '86400',
};

export function widgetOptionsResponse(): Response {
  return new Response(null, { status: 204, headers: WIDGET_CORS_HEADERS });
}

export function addWidgetCors(response: Response): Response {
  const headers = new Headers(response.headers);
  Object.entries(WIDGET_CORS_HEADERS).forEach(([k, v]) => headers.set(k, v));
  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers,
  });
}

export function withWidgetCors(handler: RouteHandler): RouteHandler {
  return async (req: Request, context: RouteContext): Promise<Response> => {
    if (req.method === 'OPTIONS') {
      return widgetOptionsResponse();
    }
    const response = await handler(req, context);
    return addWidgetCors(response);
  };
}
