import { serializeForHtml } from "@wrnexus/security";
import { escapeHtml } from "@wrnexus/core";
import { createRequestStoreContainer } from "@wrnexus/store/server";
import type { StoreContainer } from "@wrnexus/store";

const containers = new WeakMap<object, StoreContainer>();

export function requestStoreContainer(request: object, routeId?: string): StoreContainer {
  const existing = containers.get(request);
  if (existing) return existing;
  const created: StoreContainer = createRequestStoreContainer(request, routeId);
  containers.set(request, created);
  return created;
}

export async function disposeRequestStores(request: object): Promise<void> {
  const container = containers.get(request);
  if (!container) return;
  containers.delete(request);
  await container.dispose();
}

export function renderStoreHydration(container: StoreContainer, nonce?: string): string {
  const json = serializeForHtml(container.serialize());
  return `<script type="application/json" data-wrnexus-store-hydration${nonce ? ` nonce="${escapeHtml(nonce)}"` : ""}>${json}</script>`;
}
