// Generated by bynkc — do not edit by hand.
// context commerce.orders

import { Ok, Err, Some, None, type Result, type Option, type ValidationError, type DurableObjectState, type DurableObjectNamespace, StateRegistry, makeAgent, rehydrationViolation, type JsonValue, type BoundaryError } from "../runtime.js";

import { CustomerId as __CommonsCustomerId, OrderId as __CommonsOrderId } from "./identifiers.js";

export type CustomerId = __CommonsCustomerId & { readonly __ctxBrand: "commerce.orders" };
export const CustomerId = {
  of(value: string): Result<CustomerId, ValidationError> { return __CommonsCustomerId.of(value) as unknown as Result<CustomerId, ValidationError>; },
  unsafe(value: string): CustomerId { return __CommonsCustomerId.unsafe(value) as unknown as CustomerId; },
};
export type OrderId = __CommonsOrderId & { readonly __ctxBrand: "commerce.orders" };
export const OrderId = {
  of(value: string): Result<OrderId, ValidationError> { return __CommonsOrderId.of(value) as unknown as Result<OrderId, ValidationError>; },
  unsafe(value: string): OrderId { return __CommonsOrderId.unsafe(value) as unknown as OrderId; },
};

/**
 * Orders context. Each order is an agent instance keyed by OrderId.
 */

export type OrderError =
    { readonly tag: "EmptyCart" }
  | { readonly tag: "TooManyItems" }
  | { readonly tag: "OutOfStock" };

export const OrderError = {
  EmptyCart: { tag: "EmptyCart" } as OrderError,
  TooManyItems: { tag: "TooManyItems" } as OrderError,
  OutOfStock: { tag: "OutOfStock" } as OrderError,
};

export type OrderStatus =
    { readonly tag: "Pending" }
  | { readonly tag: "Placed" }
  | { readonly tag: "Cancelled" };

export const OrderStatus = {
  Pending: { tag: "Pending" } as OrderStatus,
  Placed: { tag: "Placed" } as OrderStatus,
  Cancelled: { tag: "Cancelled" } as OrderStatus,
};

export interface Inventory {
  check(productId: CustomerId): Promise<Result<number, OrderError>>;
}

export const InventoryToken: unique symbol = Symbol("Inventory");

export class StubInventory implements Inventory {
  async check(productId: CustomerId): Promise<Result<number, OrderError>> {
    return Ok(100);
  }
}

export const StubInventoryProvider = { token: InventoryToken, factory: () => new StubInventory() };

export interface OrderState {
  readonly status: Option<OrderStatus>;
  readonly items: number;
}

const __OrderRegistry = new StateRegistry();
function __zeroOfOrderState(): OrderState { return { status: None, items: 0 }; }

function __rehydrateOrderState(s: OrderState): void {
  { const __r = deserialise_Option_OrderStatus((s.status as unknown as JsonValue), "status"); if (__r.tag === "Err") throw rehydrationViolation("Order", __r.error); }
  { const __r = ((__v) => typeof __v === "number" && Number.isInteger(__v) ? Ok(__v) : Err({ kind: "StructuralMismatch", path: "items", expected: "number", actual: typeof __v } as BoundaryError))((s.items as unknown as JsonValue)); if (__r.tag === "Err") throw rehydrationViolation("Order", __r.error); }
}

export class Order {
  state: DurableObjectState;
  constructor(state: DurableObjectState) {
    this.state = state;
  }

  private async loadState(): Promise<OrderState> {
    const stored = await this.state.storage.get<OrderState>("state");
    if (stored === undefined) return __zeroOfOrderState();
    const __merged = { ...__zeroOfOrderState(), ...stored };
    __rehydrateOrderState(__merged);
    return __merged;
  }

  private async commitState(s: OrderState): Promise<void> {
    await this.state.storage.put("state", s);
  }

  async status(deps: {}): Promise<Option<OrderStatus>> {
    const __state = await this.loadState();
    return __state.status;
  }

  async addItem(productId: CustomerId, quantity: number, deps: { Inventory: Inventory }): Promise<Result<void, OrderError>> {
    const __state = { ...(await this.loadState()) };
    const __result = await (async () => {
      const stockResult = await deps.Inventory.check(productId);
      const __r0 = stockResult;
      if (__r0.tag === "Err") return __r0;
      const stock = __r0.value;
      if (stock < quantity) {
        return Err(OrderError.OutOfStock);
      } else {
        if (__state.items >= 50) {
          return Err(OrderError.TooManyItems);
        } else {
          const cur = __state.items;
          __state.items = cur + quantity;
          return Ok(undefined);
        }
      }
    })();
    await this.commitState(__state);
    return __result;
  }

}

export function __makeOrder(key: OrderId, env?: { ORDER?: DurableObjectNamespace }): Order {
  return makeAgent(__OrderRegistry, env?.ORDER, key, (state) => new Order(state));
}

export function __resetAgents(): void {
  __OrderRegistry.reset();
}

export function serialise_OrderStatus(value: OrderStatus): JsonValue {
  switch (value.tag) {
    case "Pending":
      return { kind: "Pending" };
    case "Placed":
      return { kind: "Placed" };
    case "Cancelled":
      return { kind: "Cancelled" };
  }
}

export function deserialise_OrderStatus(json: JsonValue, path: string = "$"): Result<OrderStatus, BoundaryError> {
  if (typeof json !== "object" || json === null || Array.isArray(json)) {
    return Err({ kind: "StructuralMismatch", path, expected: "object", actual: typeof json });
  }
  const obj = json as { [k: string]: JsonValue };
  const kind = obj["kind"];
  switch (kind) {
    case "Pending":
      return Ok({ tag: "Pending" } as OrderStatus);
    case "Placed":
      return Ok({ tag: "Placed" } as OrderStatus);
    case "Cancelled":
      return Ok({ tag: "Cancelled" } as OrderStatus);
    default:
      return Err({ kind: "StructuralMismatch", path, expected: "sum variant kind", actual: String(kind) });
  }
}


export function serialise_Option_OrderStatus(value: Option<OrderStatus>): JsonValue {
  if (value.tag === "Some") return { kind: "Some", value: serialise_OrderStatus(value.value) };
  return { kind: "None" };
}

export function deserialise_Option_OrderStatus(json: JsonValue, path: string = "$"): Result<Option<OrderStatus>, BoundaryError> {
  if (typeof json !== "object" || json === null || Array.isArray(json)) {
    return Err({ kind: "StructuralMismatch", path, expected: "object", actual: typeof json });
  }
  const obj = json as { [k: string]: JsonValue };
  if (obj["kind"] === "Some") {
  const __r_v = deserialise_OrderStatus(obj["value"], `${path}.value`);
  if (__r_v.tag === "Err") return __r_v;
  const __v = __r_v.value;
    return Ok(Some(__v) as Option<OrderStatus>);
  } else if (obj["kind"] === "None") {
    return Ok(None as Option<OrderStatus>);
  }
  return Err({ kind: "StructuralMismatch", path, expected: "Some | None", actual: String(obj["kind"]) });
}

