// 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 } from "../runtime.js";

export type OrderId = string & { readonly __brand: "commerce.orders.OrderId" };

export const OrderId = {
  of(value: string): Result<OrderId, ValidationError> {
    return Ok(value as OrderId);
  },
  unsafe(value: string): OrderId {
    return value as OrderId;
  },
};

export type OrderError =
    { readonly tag: "NotPlaced" };

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

export interface OrderState {
  readonly placed: boolean;
}

const __OrderRegistry = new StateRegistry();
function __zeroOfOrderState(): OrderState { return { placed: false }; }

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 place(amount: number, deps: {}): Promise<Result<void, OrderError>> {
    const currentState = await this.loadState();
    if (amount > 0) {
      await this.commitState({ ...currentState, placed: true });
      return Ok(undefined);
    } else {
      return Err(OrderError.NotPlaced);
    }
  }

}

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();
}

