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

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

/**
 * A fresh `Slot` key must read `value == None`: Option state zero-initialises.
 */

export type Label = string & { readonly __brand: "demo.slot.Label" };

export const Label = {
  of(value: string): Result<Label, ValidationError> {
    if (!new RegExp("^" + "[a-z0-9]{1,16}" + "$").test(value)) {
      return Err({ field: "Label", message: "must match /[a-z0-9]{1,16}/", value });
    }
    return Ok(value as Label);
  },
  unsafe(value: string): Label {
    return value as Label;
  },
};

export type SlotError =
    { readonly tag: "Empty" };

export const SlotError = {
  Empty: { tag: "Empty" } as SlotError,
};

export interface SlotState {
  readonly value: Option<number>;
}

const __SlotRegistry = new StateRegistry();
function __zeroOfSlotState(): SlotState { return { value: None }; }

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

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

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

  async resolve(deps: {}): Promise<Result<number, SlotError>> {
    const currentState = await this.loadState();
    switch (currentState.value.tag) {
      case "Some": {
        const v = currentState.value.value;
        return Ok(v);
      }
      case "None": {
        return Err(SlotError.Empty);
      }
    }
    throw new Error("non-exhaustive match");
  }

}

export function __makeSlot(key: Label, env?: { SLOT?: DurableObjectNamespace }): Slot {
  return makeAgent(__SlotRegistry, env?.SLOT, key, (state) => new Slot(state));
}

export const resolve = {
  async call(id: Label, deps: {}): Promise<Result<number, SlotError>> {
    const slot = __makeSlot(id);
    const outcome = await slot.resolve(deps);
    return outcome;
  },
};

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

export interface DemoSlotDeps {
}

export function makeSurface(deps: DemoSlotDeps) {
  return {
    async resolve(id: Label): Promise<Result<number, SlotError>> {
      return resolve.call(id, deps);
    },
  };
}

