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

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 AudienceState {
  readonly members: Record<string, boolean>;
}

const __AudienceRegistry = new StateRegistry();
function __zeroOfAudienceState(): AudienceState { return { members: {} }; }

function __rehydrateAudienceState(s: AudienceState): void {
  for (const __k of Object.keys(s.members)) { const __r = ((__v) => typeof __v === "string" ? Ok(__v) : Err({ kind: "StructuralMismatch", path: "members", expected: "string", actual: typeof __v } as BoundaryError))((__k as unknown as JsonValue)); if (__r.tag === "Err") throw rehydrationViolation("Audience", __r.error); }
}

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

  private async loadState(): Promise<AudienceState> {
    const stored = await this.state.storage.get<AudienceState>("state");
    if (stored === undefined) return __zeroOfAudienceState();
    const __merged = { ...__zeroOfAudienceState(), ...stored };
    __rehydrateAudienceState(__merged);
    return __merged;
  }

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

  async join(who: string, deps: {}): Promise<void> {
    const __state = { ...(await this.loadState()) };
    const __result = await (async () => {
      const __r0 = await ((__state.members[who] = true), undefined);
      return undefined;
    })();
    await this.commitState(__state);
    return __result;
  }

  async leave(who: string, deps: {}): Promise<void> {
    const __state = { ...(await this.loadState()) };
    const __result = await (async () => {
      const __r0 = await ((delete __state.members[who]), undefined);
      return undefined;
    })();
    await this.commitState(__state);
    return __result;
  }

  async isMember(who: string, deps: {}): Promise<boolean> {
    const __state = await this.loadState();
    const here = await ((who) in __state.members);
    return here;
  }

  async size(deps: {}): Promise<number> {
    const __state = await this.loadState();
    const n = await Object.keys(__state.members).length;
    return n;
  }

}

export function __makeAudience(key: string, env?: { AUDIENCE?: DurableObjectNamespace }): Audience {
  return makeAgent(__AudienceRegistry, env?.AUDIENCE, key, (state) => new Audience(state));
}

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

