import { NextResponse } from "next/server";
import { withCorrelationId } from "@/lib/correlation-id";

export interface ApiErrorEnvelope {
  error: {
    code: string;
    message: string;
    correlationId: string;
    details?: unknown;
  };
}

export function apiError(
  status: number,
  code: string,
  message: string,
  correlationId: string,
  details?: unknown,
): ApiErrorEnvelope {
  return {
    error: {
      code,
      message,
      correlationId,
      ...(details !== undefined ? { details } : {}),
    },
  };
}

export function apiErrorResponse(
  status: number,
  code: string,
  message: string,
  correlationId: string,
  details?: unknown,
): NextResponse {
  const body = apiError(status, code, message, correlationId, details);
  return withCorrelationId(NextResponse.json(body, { status }), correlationId);
}
