import type { MiddlewareHandler } from 'hono';

export const originMiddleware: MiddlewareHandler = function (ctx, next) {
  let origin = ctx.req.header('origin');

  if (!origin) {
    const referer = ctx.req.header('referer');
    if (referer) {
      try {
        const url = new URL(referer);
        origin = url.origin;
      } catch {}
    }
  }

  ctx.set('origin', origin);
  return next();
};
