import { ZodError } from "zod";

export type ErrorResponseBody = {
  error: {
    message: string;
    code?: string;
    details?: unknown;
  };
};

export class HttpError extends Error {
  status: number;
  code?: string;
  details?: unknown;

  constructor(message: string, opts: { status: number; code?: string; details?: unknown }) {
    super(message);
    this.name = "HttpError";
    this.status = opts.status;
    this.code = opts.code;
    this.details = opts.details;
  }
}

export function isZodError(err: unknown): err is ZodError {
  return err instanceof ZodError;
}

export function toHttpError(err: unknown): HttpError {
  if (err instanceof HttpError) return err;
  if (isZodError(err)) {
    return new HttpError("Invalid request", {
      status: 400,
      code: "VALIDATION_ERROR",
      details: err.flatten(),
    });
  }
  if (err instanceof Error) {
    return new HttpError(err.message, { status: 500, code: "INTERNAL_ERROR" });
  }
  return new HttpError("Unknown error", { status: 500, code: "INTERNAL_ERROR" });
}
