/*
 * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
 */

import * as z from "zod/v3";
import {
  collectExtraKeys as collectExtraKeys$,
  safeParse,
} from "../lib/schemas.js";
import { Result as SafeParseResult } from "../types/fp.js";
import * as types from "../types/primitives.js";
import { SDKValidationError } from "./sdkvalidationerror.js";
import { VercelError } from "./vercelerror.js";

/**
 * Error details.
 */
export type ErrorT = {
  /**
   * Stable machine-readable error code.
   */
  code: string;
  /**
   * Human-readable error message.
   */
  message: string;
  additionalProperties?: { [k: string]: any } | undefined;
};

/**
 * Error response returned by a Connect API operation.
 */
export type ConnectErrorData = {
  /**
   * Error details.
   */
  error: ErrorT;
};

/**
 * Error response returned by a Connect API operation.
 */
export class ConnectError extends VercelError {
  /**
   * Error details.
   */
  error: ErrorT;

  /** The original data that was passed to this error instance. */
  data$: ConnectErrorData;

  constructor(
    err: ConnectErrorData,
    httpMeta: { response: Response; request: Request; body: string },
  ) {
    const message = err.error?.message
      || `API error occurred: ${JSON.stringify(err)}`;
    super(message, httpMeta);
    this.data$ = err;
    this.error = err.error;

    this.name = "ConnectError";
  }
}

/** @internal */
export const ErrorT$inboundSchema: z.ZodType<ErrorT, z.ZodTypeDef, unknown> =
  collectExtraKeys$(
    z.object({
      code: types.string(),
      message: types.string(),
    }).catchall(z.any()),
    "additionalProperties",
    true,
  );

export function errorFromJSON(
  jsonString: string,
): SafeParseResult<ErrorT, SDKValidationError> {
  return safeParse(
    jsonString,
    (x) => ErrorT$inboundSchema.parse(JSON.parse(x)),
    `Failed to parse 'ErrorT' from JSON`,
  );
}

/** @internal */
export const ConnectError$inboundSchema: z.ZodType<
  ConnectError,
  z.ZodTypeDef,
  unknown
> = z.object({
  error: z.lazy(() => ErrorT$inboundSchema),
  request$: z.instanceof(Request),
  response$: z.instanceof(Response),
  body$: z.string(),
})
  .transform((v) => {
    return new ConnectError(v, {
      request: v.request$,
      response: v.response$,
      body: v.body$,
    });
  });
