/**
 * Binds the request locale to the SSR render via `AsyncLocalStorage`.
 *
 * `usePrefsStore` is module-level state shared by every request in an isolate,
 * so it cannot carry a per-request locale. The store therefore seeds to `'he'`
 * on the server, and any island rendered without an explicit `locale` prop
 * emits Hebrew server-side and the request locale client-side — React #418.
 *
 * Astro's streaming renderer starts the render inside `new ReadableStream({
 * start })`, which runs synchronously within the middleware's `await next()`.
 * Every island's `renderToString` is therefore a continuation of an async
 * resource created inside `run()` and inherits the store, even though the
 * response body completes after the middleware returns.
 */

import { AsyncLocalStorage } from 'node:async_hooks';
import { setRequestLocaleResolver } from '@/lib/i18n/request-locale';
import type { Locale } from '@/lib/i18n';

const storage = new AsyncLocalStorage<Locale>();

setRequestLocaleResolver(() => storage.getStore());

export function runWithRequestLocale<T>(locale: Locale, render: () => T): T {
  return storage.run(locale, render);
}
