/**
 * Plain-script fixture for `server.runServiceContext(...)`.
 *
 * Reproduces the crash pattern exactly: a plain script under top-level await
 * that awaits an async helper which builds service work through the server.
 * `createServiceContext(...)` enters the ambient frame with
 * `AsyncLocalStorage.enterWith`, and resuming that frame across top-level
 * await segfaults Bun 1.3.x; `runServiceContext(...)` scopes the frame with
 * `AsyncLocalStorage.run` so this script must exit 0 and print the marker.
 */

import { getActiveRequestContext } from "../request-context.js";
import { createServer } from "../server.js";
import { defineServerContext } from "../server-context.js";

type ScriptContext = {
  actor: { type: "service"; id: string };
  ports: Record<string, never>;
};

const appContext = defineServerContext<ScriptContext, Record<string, never>>()({
  request: async ({ ports }) => ({
    actor: { type: "service", id: "request" },
    ports,
  }),
  service: ({ ports }) => ({
    actor: { type: "service", id: "script-service" },
    ports,
  }),
});

async function runScriptWork(): Promise<string> {
  const server = await createServer<ScriptContext, Record<string, never>>({
    ports: {},
    context: appContext,
  });

  return server.runServiceContext(async (ctx) => {
    const ambient = getActiveRequestContext();
    return `${ctx.actor.id}:${ambient?.actor?.id ?? "no-ambient"}`;
  });
}

const marker = await runScriptWork();
console.log(`run-service-context-script:${marker}`);
