import { listNativeCases, listNativeRuns, readNativeAggregate, readNativeEvents, readNativeRun, startNativeRun } from "./caserun-native-fixtures";

const port = Number(requiredEnv("HWLAB_CASERUN_NATIVE_PORT"));
const hostname = requiredEnv("HWLAB_CASERUN_NATIVE_HOST");

function json(data: unknown, status = 200): Response {
  return Response.json(data, { status, headers: { "cache-control": "no-store" } });
}

function notFound(kind: string, id?: string): Response {
  return json({ ok: false, mode: "native-test", error: { code: `${kind}-not-found`, message: id ? `${kind} ${id} not found` : `${kind} not found` } }, 404);
}

function authSession(): Record<string, unknown> {
  return {
    ok: true,
    authenticated: true,
    mode: "native-test",
    sessionKind: "native-test",
    user: { id: "native-admin", username: "native-admin", displayName: "Native Admin", role: "admin", status: "active" },
    capabilities: { admin: "available" },
    access: { nav: { profileId: "native-test", allowedIds: ["*"], valuesRedacted: true } },
    valuesRedacted: true
  };
}

const server = Bun.serve({
  hostname,
  port,
  development: true,
  async fetch(request) {
    const url = new URL(request.url);
    if (request.method === "GET" && url.pathname === "/health") return json({ ok: true, mode: "native-test" });
    if (request.method === "POST" && url.pathname === "/auth/login") {
      return Response.json(authSession(), { headers: { "cache-control": "no-store", "set-cookie": "hwlab_session=native-test; Path=/; HttpOnly; SameSite=Lax" } });
    }
    if (request.method === "GET" && url.pathname === "/auth/session") return json(authSession());
    if (request.method === "GET" && url.pathname === "/v1/caserun/cases") return json(listNativeCases());
    if (request.method === "GET" && url.pathname === "/v1/caserun/runs") {
      return json(listNativeRuns({
        status: url.searchParams.get("status") ?? undefined,
        limit: url.searchParams.has("limit") ? Number(url.searchParams.get("limit")) : undefined,
        cursor: url.searchParams.get("cursor") ?? undefined
      }));
    }
    if (request.method === "POST" && url.pathname === "/v1/caserun/runs") {
      const body = await request.json().catch(() => null) as { caseId?: string } | null;
      if (!body?.caseId) return json({ ok: false, mode: "native-test", error: { code: "case-id-required", message: "caseId is required" } }, 400);
      const run = startNativeRun(body.caseId);
      return run ? json(run, 202) : notFound("case", body.caseId);
    }
    const eventsMatch = url.pathname.match(/^\/v1\/caserun\/runs\/([^/]+)\/events$/);
    if (request.method === "GET" && eventsMatch) {
      const runId = decodeURIComponent(eventsMatch[1]!);
      const events = readNativeEvents(runId);
      return events ? json(events) : notFound("run", runId);
    }
    const aggregateMatch = url.pathname.match(/^\/v1\/caserun\/runs\/([^/]+)\/aggregate$/);
    if (request.method === "GET" && aggregateMatch) {
      const runId = decodeURIComponent(aggregateMatch[1]!);
      const aggregate = readNativeAggregate(runId);
      return aggregate ? json(aggregate) : notFound("run", runId);
    }
    const runMatch = url.pathname.match(/^\/v1\/caserun\/runs\/([^/]+)$/);
    if (request.method === "GET" && runMatch) {
      const runId = decodeURIComponent(runMatch[1]!);
      const run = readNativeRun(runId);
      return run ? json(run) : notFound("run", runId);
    }
    return notFound("route", url.pathname);
  }
});

console.log(JSON.stringify({ event: "caserun-native-listening", mode: "native-test", hostname: server.hostname, port: server.port }));

function requiredEnv(name: string): string {
  const value = String(process.env[name] ?? "").trim();
  if (!value) throw new Error(`${name} is required from the CLI-managed YAML profile`);
  return value;
}
