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

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 interface CounterState {
  readonly n: number;
}

const __CounterRegistry = new StateRegistry();
function __zeroOfCounterState(): CounterState { return { n: 0 }; }

function __rehydrateCounterState(s: CounterState): void {
  { const __r = ((__v) => typeof __v === "number" && Number.isInteger(__v) ? Ok(__v) : Err({ kind: "StructuralMismatch", path: "n", expected: "number", actual: typeof __v } as BoundaryError))((s.n as unknown as JsonValue)); if (__r.tag === "Err") throw rehydrationViolation("Counter", __r.error); }
}

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");
    if (stored === undefined) return __zeroOfCounterState();
    const __merged = { ...__zeroOfCounterState(), ...stored };
    __rehydrateCounterState(__merged);
    return __merged;
  }

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

  async increment(deps: {}): Promise<number> {
    const __state = { ...(await this.loadState()) };
    const __result = await (async () => {
      const __r0 = await (() => { __state.n = ((c) => c + 1)(__state.n); return undefined; })();
      return __state.n;
    })();
    await this.commitState(__state);
    return __result;
  }

  async current(deps: {}): Promise<number> {
    const __state = await this.loadState();
    return __state.n;
  }

}

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

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

