import type { ApiErrorResponse } from "./types";

interface HttpErrorOptions {
  httpStatus: number;
  code: string;
  message: string;
  details?: unknown | null;
  requestId?: string;
  cause?: unknown;
}

export class HttpError extends Error {
  readonly httpStatus: number;
  readonly code: string;
  readonly details: unknown | null;
  readonly requestId: string;
  override readonly cause?: unknown;

  constructor(options: HttpErrorOptions) {
    super(options.message);
    this.name = "HttpError";
    this.httpStatus = options.httpStatus;
    this.code = options.code;
    this.details = options.details ?? null;
    this.requestId = options.requestId ?? "";
    this.cause = options.cause;
  }
}

export function isApiErrorResponse(value: unknown): value is ApiErrorResponse {
  if (!value || typeof value !== "object") return false;
  const candidate = value as Partial<ApiErrorResponse>;
  return (
    typeof candidate.code === "string" &&
    candidate.code !== "OK" &&
    typeof candidate.message === "string" &&
    "details" in candidate &&
    typeof candidate.requestId === "string"
  );
}
