/**
 * 统一 JSON / 错误响应封装
 */

import { withCorsHeaders } from "./cors.ts";

export function jsonResponse(
  body: unknown,
  status = 200,
  extraHeaders: Record<string, string> = {},
): Response {
  return new Response(JSON.stringify(body), {
    status,
    headers: withCorsHeaders({
      "Content-Type": "application/json",
      ...extraHeaders,
    }),
  });
}

export function errorResponse(
  message: string,
  status = 500,
  opts: { traceId?: string; code?: string; details?: unknown } = {},
): Response {
  const { traceId, code, details } = opts;
  return jsonResponse(
    {
      error: true,
      code: code ?? "INTERNAL_ERROR",
      message,
      ...(details ? { details } : {}),
      ...(traceId ? { trace_id: traceId } : {}),
    },
    status,
    traceId ? { "x-trace-id": traceId } : {},
  );
}
