/**
 * Shared error model and envelope. Single shape for every API error.
 * Never leak stack traces or internal details to the client.
 */

export type ErrorDetail = Readonly<Record<string, unknown>>;

export class AppError extends Error {
  constructor(
    public readonly statusCode: number,
    public readonly code: string,
    message: string,
    public readonly details?: ReadonlyArray<ErrorDetail>,
  ) {
    super(message);
    this.name = 'AppError';
  }
}

export interface ErrorEnvelope {
  error: {
    statusCode: number;
    code: string;
    message: string;
    details?: ReadonlyArray<ErrorDetail>;
  };
  requestId: string;
}

export function errorEnvelope(
  statusCode: number,
  code: string,
  message: string,
  requestId: string,
  details?: ReadonlyArray<ErrorDetail>,
): ErrorEnvelope {
  return {
    error:
      details === undefined
        ? { statusCode, code, message }
        : { statusCode, code, message, details },
    requestId,
  };
}
