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

import * as z from "zod/v4-mini";
import { remap as remap$ } from "../../lib/primitives.js";
import { safeParse } from "../../lib/schemas.js";
import { Result as SafeParseResult } from "../../types/fp.js";
import { SDKValidationError } from "../errors/sdkvalidationerror.js";
import {
  WebhookEventType,
  WebhookEventType$inboundSchema,
} from "./webhookeventtype.js";

/**
 * A webhook event.
 *
 * @remarks
 *
 * An event represent something that happened in the system
 * that should be sent to the webhook endpoint.
 *
 * It can be delivered multiple times until it's marked as succeeded,
 * each one creating a new delivery.
 */
export type WebhookEvent = {
  /**
   * Creation timestamp of the object.
   */
  createdAt: Date;
  /**
   * Last modification timestamp of the object.
   */
  modifiedAt: Date | null;
  /**
   * The ID of the object.
   */
  id: string;
  /**
   * Last HTTP code returned by the URL. `null` if no delviery has been attempted or if the endpoint was unreachable.
   */
  lastHttpCode?: number | null | undefined;
  /**
   * Whether this event was successfully delivered. `null` if no delivery has been attempted.
   */
  succeeded?: boolean | null | undefined;
  /**
   * Whether this event was skipped because the webhook endpoint was disabled.
   */
  skipped: boolean;
  /**
   * The payload of the webhook event.
   */
  payload: string | null;
  type: WebhookEventType;
  /**
   * Whether this event is archived. Archived events can't be redelivered, and the payload is not accessible anymore.
   */
  isArchived: boolean;
};

/** @internal */
export const WebhookEvent$inboundSchema: z.ZodMiniType<WebhookEvent, unknown> =
  z.pipe(
    z.object({
      created_at: z.pipe(
        z.iso.datetime({ offset: true }),
        z.transform(v => new Date(v)),
      ),
      modified_at: z.nullable(
        z.pipe(z.iso.datetime({ offset: true }), z.transform(v => new Date(v))),
      ),
      id: z.string(),
      last_http_code: z.optional(z.nullable(z.int())),
      succeeded: z.optional(z.nullable(z.boolean())),
      skipped: z.boolean(),
      payload: z.nullable(z.string()),
      type: WebhookEventType$inboundSchema,
      is_archived: z.boolean(),
    }),
    z.transform((v) => {
      return remap$(v, {
        "created_at": "createdAt",
        "modified_at": "modifiedAt",
        "last_http_code": "lastHttpCode",
        "is_archived": "isArchived",
      });
    }),
  );

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