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

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

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 type OrderError =
    { readonly tag: "AlreadyPlaced" }
  | { readonly tag: "AlreadyCancelled" };

export const OrderError = {
  AlreadyPlaced: { tag: "AlreadyPlaced" } as OrderError,
  AlreadyCancelled: { tag: "AlreadyCancelled" } as OrderError,
};

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

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

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");
    return stored ?? __zeroOfOrderState();
  }

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

  async addItem(quantity: number, deps: {}): Promise<Result<void, OrderError>> {
    const currentState = await this.loadState();
    await this.commitState({ ...currentState, items: currentState.items + quantity });
    return Ok(undefined);
  }

  async place(deps: {}): Promise<Result<void, OrderError>> {
    const currentState = await this.loadState();
    switch (currentState.status.tag) {
      case "Pending": {
        await this.commitState({ ...currentState, status: OrderStatus.Placed });
        return Ok(undefined);
      }
      case "Placed": {
        return Err(OrderError.AlreadyPlaced);
      }
      case "Cancelled": {
        return Err(OrderError.AlreadyCancelled);
      }
    }
    throw new Error("non-exhaustive match");
  }

}

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

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

