import type { MiddlewareHandler } from 'hono';

export type CorsMode = 'same-origin' | 'public-read';

const SAME_ORIGIN_ORIGINS = new Set([
  'https://my.transquinnftw.com',
  'http://my.quinn.apricot.local',
  'http://plum.local:8765',
  'http://localhost:8765',
]);

export function corsMiddleware(mode: CorsMode): MiddlewareHandler {
  return async (c, next) => {
    const origin = c.req.header('origin') ?? '';

    let allowOrigin: string;
    if (mode === 'public-read') {
      allowOrigin = '*';
    } else {
      allowOrigin = SAME_ORIGIN_ORIGINS.has(origin) ? origin : '';
    }

    if (c.req.method === 'OPTIONS') {
      const headers: Record<string, string> = {
        'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type,Authorization',
        'Access-Control-Max-Age': '86400',
      };
      if (allowOrigin) headers['Access-Control-Allow-Origin'] = allowOrigin;
      if (mode === 'same-origin') headers['Access-Control-Allow-Credentials'] = 'true';
      return new Response(null, { status: 204, headers });
    }

    await next();

    if (allowOrigin) {
      c.res.headers.set('Access-Control-Allow-Origin', allowOrigin);
      if (mode === 'same-origin') {
        c.res.headers.set('Access-Control-Allow-Credentials', 'true');
      }
    }
  };
}
