/**
 * Canonical JSON error response helpers.
 *
 * Two variants:
 *   jsonError       → flat:   { ok: false, error: string, code: string }
 *                    Used by cart routes, auth, and new code.
 *   jsonErrorNested → nested: { ok: false, error: { code, message } }
 *                    Used by confirm.ts — kept for client contract compatibility.
 */

import { respondError } from '@/server/api/error-envelope.js';

export function jsonError(
  code: string,
  message: string,
  status: number,
  headers: Record<string, string> = {},
): Response {
  const response = respondError(code, message, status);
  for (const [key, value] of Object.entries(headers)) {
    response.headers.set(key, value);
  }
  return response;
}

export function jsonErrorNested(
  code: string,
  message: string,
  status: number,
  headers: Record<string, string> = {},
): Response {
  return new Response(JSON.stringify({ ok: false, error: { code, message } }), {
    status,
    headers: { 'Content-Type': 'application/json', ...headers },
  });
}
