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

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

export type CartId = string & { readonly __brand: "cart.CartId" };

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

export interface CartEntityState {
  readonly items: number;
}

const __CartEntityRegistry = new StateRegistry();
function __zeroOfCartEntityState(): CartEntityState { return { items: 0 }; }

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

  private async loadState(): Promise<CartEntityState> {
    const stored = await this.state.storage.get<CartEntityState>("state");
    return stored ?? __zeroOfCartEntityState();
  }

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

  async total(deps: {}): Promise<number> {
    const currentState = await this.loadState();
    return currentState.items;
  }

  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname.startsWith("/_bynk/agent/")) {
      const methodName = url.pathname.slice("/_bynk/agent/".length);
      const { args, deps } = (await request.json()) as { args: unknown[]; deps: unknown };
      const result = await (this as any)[methodName](...args, deps);
      return new Response(JSON.stringify(result), { headers: { "content-type": "application/json" } });
    }
    return new Response("Not Found", { status: 404 });
  }

}

export function __makeCartEntity(key: CartId, env?: { CART_ENTITY?: DurableObjectNamespace }): CartEntity {
  return makeAgent(__CartEntityRegistry, env?.CART_ENTITY, key, (state) => new CartEntity(state));
}

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

