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

import * as z from "zod/v4-mini";
import { safeParse } from "../../lib/schemas.js";
import { Result as SafeParseResult } from "../../types/fp.js";
import { SDKValidationError } from "../errors/sdkvalidationerror.js";
import {
  Order,
  Order$inboundSchema,
  Order$Outbound,
  Order$outboundSchema,
} from "./order.js";

/**
 * Sent when a new order is created.
 *
 * @remarks
 *
 * A new order is created when:
 *
 * * A customer purchases a one-time product. In this case, `billing_reason` is set to `purchase`.
 * * A customer starts a subscription. In this case, `billing_reason` is set to `subscription_create`.
 * * A subscription is renewed. In this case, `billing_reason` is set to `subscription_cycle`.
 * * A subscription is upgraded or downgraded with an immediate proration invoice. In this case, `billing_reason` is set to `subscription_update`.
 *
 * > [!WARNING]
 * > The order might not be paid yet, so the `status` field might be `pending`.
 *
 * **Discord & Slack support:** Full
 */
export type WebhookOrderCreatedPayload = {
  type: "order.created";
  timestamp: Date;
  data: Order;
};

/** @internal */
export const WebhookOrderCreatedPayload$inboundSchema: z.ZodMiniType<
  WebhookOrderCreatedPayload,
  unknown
> = z.object({
  type: z.literal("order.created"),
  timestamp: z.pipe(
    z.iso.datetime({ offset: true }),
    z.transform(v => new Date(v)),
  ),
  data: Order$inboundSchema,
});
/** @internal */
export type WebhookOrderCreatedPayload$Outbound = {
  type: "order.created";
  timestamp: string;
  data: Order$Outbound;
};

/** @internal */
export const WebhookOrderCreatedPayload$outboundSchema: z.ZodMiniType<
  WebhookOrderCreatedPayload$Outbound,
  WebhookOrderCreatedPayload
> = z.object({
  type: z.literal("order.created"),
  timestamp: z.pipe(z.date(), z.transform(v => v.toISOString())),
  data: Order$outboundSchema,
});

export function webhookOrderCreatedPayloadToJSON(
  webhookOrderCreatedPayload: WebhookOrderCreatedPayload,
): string {
  return JSON.stringify(
    WebhookOrderCreatedPayload$outboundSchema.parse(webhookOrderCreatedPayload),
  );
}
export function webhookOrderCreatedPayloadFromJSON(
  jsonString: string,
): SafeParseResult<WebhookOrderCreatedPayload, SDKValidationError> {
  return safeParse(
    jsonString,
    (x) => WebhookOrderCreatedPayload$inboundSchema.parse(JSON.parse(x)),
    `Failed to parse 'WebhookOrderCreatedPayload' from JSON`,
  );
}
