/**
 * 统一 CORS 头与预检处理
 */

export const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers":
    "authorization, x-client-info, apikey, content-type, x-trace-id",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Max-Age": "86400",
};

/** 处理 OPTIONS 预检请求；命中则直接返回 Response，否则返回 null */
export function handlePreflight(req: Request): Response | null {
  if (req.method === "OPTIONS") {
    return new Response(null, { status: 204, headers: corsHeaders });
  }
  return null;
}

/** 在已有 headers 基础上叠加 CORS（保留 Content-Type 等） */
export function withCorsHeaders(extra: HeadersInit = {}): HeadersInit {
  return { ...corsHeaders, ...extra };
}
