// Generated by bynkc — do not edit by hand.
// context demo.agt

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

export type Id = number & { readonly __brand: "demo.agt.Id" };

export const Id = {
  of(value: number): Result<Id, ValidationError> {
    if (!Number.isInteger(value)) {
      return Err({ field: "Id", message: "must be an integer", value });
    }
    if (!(value >= 0)) {
      return Err({ field: "Id", message: "must be non-negative", value });
    }
    return Ok(value as Id);
  },
  unsafe(value: number): Id {
    return value as Id;
  },
};

export interface CounterState {
  readonly count: number;
  readonly label: string;
}

const __CounterRegistry = new StateRegistry();
function __zeroOfCounterState(): CounterState { return { count: 0, label: "" }; }

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

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

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

  async describe(deps: {}): Promise<string> {
    const currentState = await this.loadState();
    return currentState.label;
  }

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

}

export function __makeCounter(key: Id, env?: { COUNTER?: DurableObjectNamespace }): Counter {
  return makeAgent(__CounterRegistry, env?.COUNTER, key, (state) => new Counter(state));
}

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

