// Generated by bynkc — do not edit by hand.
// context shop.inventory

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 Reservation {
  readonly id: string;
  readonly qty: number;
}

export const Reservation = {
};

export interface InventoryState {
  readonly reservations: Record<string, Reservation>;
}

const __InventoryRegistry = new StateRegistry();
function __zeroOfInventoryState(): InventoryState { return { reservations: {} }; }

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

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

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

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

  async bigQuantities(deps: {}): Promise<readonly number[]> {
    const __state = await this.loadState();
    return ((() => ((() => Object.values(__state.reservations).filter((__x) => ((r) => r.qty > 0)(__x))))().map((__x) => ((r) => r.qty)(__x))))();
  }

  async pageById(deps: {}): Promise<readonly Reservation[]> {
    const __state = await this.loadState();
    return ((() => ((() => ((() => [...Object.values(__state.reservations)].sort((__a, __b) => { const __ka = ((r) => r.id)(__a), __kb = ((r) => r.id)(__b); return __ka < __kb ? -1 : __ka > __kb ? 1 : 0; })))().slice(Math.max(0, 1))))().slice(0, Math.max(0, 10))))();
  }

  async total(deps: {}): Promise<number> {
    const __state = await this.loadState();
    return Object.values(__state.reservations).reduce((__s: number, __x) => __s + ((r) => r.qty)(__x), 0);
  }

  async largest(deps: {}): Promise<Option<number>> {
    const __state = await this.loadState();
    return (() => { const __a = Object.values(__state.reservations); if (__a.length === 0) return None; let __m = ((r) => r.qty)(__a[0]); for (const __x of __a) { const __k = ((r) => r.qty)(__x); if (__k > __m) __m = __k; } return Some(__m); })();
  }

  async howMany(deps: {}): Promise<number> {
    const __state = await this.loadState();
    return ((() => Object.values(__state.reservations).filter((__x) => ((r) => r.qty > 0)(__x))))().length;
  }

  async anyBig(deps: {}): Promise<boolean> {
    const __state = await this.loadState();
    return Object.values(__state.reservations).some((__x) => ((r) => r.qty > 100)(__x));
  }

  async pending(deps: {}): Promise<readonly Reservation[]> {
    const __state = await this.loadState();
    const q = (() => Object.values(__state.reservations).filter((__x) => ((r) => r.qty > 0)(__x)));
    return ((() => (() => { const __seen = new Set(); const __out: any[] = []; for (const __x of (q)()) { const __k = ((r) => r.id)(__x); if (!__seen.has(__k)) { __seen.add(__k); __out.push(__x); } } return __out; })()))();
  }

  async firstBig(deps: {}): Promise<Reservation> {
    const __state = await this.loadState();
    return (() => { const __a = ((() => Object.values(__state.reservations).filter((__x) => ((r) => r.qty > 50)(__x))))(); return __a.length > 0 ? __a[0] : ({ id: "none", qty: 0 }); })();
  }

}

export function __makeInventory(key: string, env?: { INVENTORY?: DurableObjectNamespace }): Inventory {
  return makeAgent(__InventoryRegistry, env?.INVENTORY, key, (state) => new Inventory(state));
}

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

export function serialise_Reservation(value: Reservation): JsonValue {
  return {
    id: value.id as JsonValue,
    qty: value.qty as JsonValue,
  };
}

export function deserialise_Reservation(json: JsonValue, path: string = "$"): Result<Reservation, BoundaryError> {
  if (typeof json !== "object" || json === null || Array.isArray(json)) {
    return Err({ kind: "StructuralMismatch", path, expected: "object", actual: typeof json });
  }
  const obj = json as { [k: string]: JsonValue };
  if (typeof obj["id"] !== "string") {
    return Err({ kind: "StructuralMismatch", path: `${path}.id`, expected: "string", actual: typeof obj["id"] });
  }
  const __id = obj["id"];
  if (typeof obj["qty"] !== "number") {
    return Err({ kind: "StructuralMismatch", path: `${path}.qty`, expected: "number", actual: typeof obj["qty"] });
  }
  if (!Number.isInteger(obj["qty"])) {
    return Err({ kind: "StructuralMismatch", path: `${path}.qty`, expected: "integer", actual: String(obj["qty"]) });
  }
  const __qty = obj["qty"];
  return Ok({ id: __id, qty: __qty } as Reservation);
}


