// 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, rehydrationViolation, type JsonValue, type BoundaryError } 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 ToggleState {
  readonly active: boolean;
}

const __ToggleRegistry = new StateRegistry();
function __zeroOfToggleState(): ToggleState { return { active: false }; }

function __rehydrateToggleState(s: ToggleState): void {
  { const __r = ((__v) => typeof __v === "boolean" ? Ok(__v) : Err({ kind: "StructuralMismatch", path: "active", expected: "boolean", actual: typeof __v } as BoundaryError))((s.active as unknown as JsonValue)); if (__r.tag === "Err") throw rehydrationViolation("Toggle", __r.error); }
}

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

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

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

  async flip(force: boolean, deps: {}): Promise<boolean> {
    const __state = { ...(await this.loadState()) };
    const __result = await (async () => {
      if (force) {
        const cur = __state.active;
        __state.active = !cur;
        return true;
      } else {
        return false;
      }
    })();
    await this.commitState(__state);
    return __result;
  }

}

export function __makeToggle(key: Id, env?: { TOGGLE?: DurableObjectNamespace }): Toggle {
  return makeAgent(__ToggleRegistry, env?.TOGGLE, key, (state) => new Toggle(state));
}

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

