// 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";

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

function __rehydrateOrderState(s: OrderState): void {
  { const __r = ((__v) => typeof __v === "boolean" ? Ok(__v) : Err({ kind: "StructuralMismatch", path: "placed", expected: "boolean", actual: typeof __v } as BoundaryError))((s.placed 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 place(amount: number, deps: {}): Promise<Result<void, OrderError>> {
    const __state = { ...(await this.loadState()) };
    const __result = await (async () => {
      if (amount > 0) {
        __state.placed = true;
        return Ok(undefined);
      } else {
        return Err(OrderError.NotPlaced);
      }
    })();
    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();
}

