import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";

const source = readFileSync(resolve(process.cwd(), "server", "dev-server.mjs"), "utf8");

function sourceBlock(startMarker: string, endMarker: string) {
  const start = source.indexOf(startMarker);
  expect(start, `Missing source marker: ${startMarker}`).toBeGreaterThanOrEqual(0);
  const end = source.indexOf(endMarker, start + startMarker.length);
  expect(end, `Missing end marker after: ${startMarker}`).toBeGreaterThan(start);
  return source.slice(start, end);
}

describe("assistant-ready Launcher admin routes", () => {
  it("keeps control-plane read behind Launcher admin guard", () => {
    expect(source).toContain('app.get("/api/admin/control-plane", requireLauncherAdmin');
    expect(source).toContain("res.json(scopeAdminSnapshot(req));");
  });

  it("keeps assistant gateway auth narrow and route-allowlisted", () => {
    expect(source).toContain('const assistantGatewayName = "ontology-core"');
    expect(source).toContain("const assistantGatewayAdminRouteAllowlist = [");
    expect(source).toContain('{ method: "GET", pattern: /^\\/api\\/admin\\/control-plane$/ }');
    expect(source).toContain('{ method: "PATCH", pattern: /^\\/api\\/admin\\/users\\/[^/?#]+\\/profile$/ }');
    expect(source).toContain('{ method: "PATCH", pattern: /^\\/api\\/admin\\/memberships\\/[^/?#]+$/ }');
    expect(source).toContain("resolveAssistantGatewayAdminContext(req)");
    expect(source).toContain("assistant_gateway_route_not_allowlisted");
    expect(source).toContain('readRequestHeader(req, "x-nodedc-assistant-actor-user-id")');
  });

  it("routes browser assistant actions through session-owned Launcher proxy context", () => {
    const block = sourceBlock('app.post("/api/assistant/actions"', 'app.get("/api/events"');
    const builderBlock = sourceBlock("function buildAssistantActionProxyCommand", "function getAiWorkspaceAssistantBaseUrl");

    expect(block).toContain("requireSession");
    expect(block).toContain("getLauncherProfileContext(req.nodedcSession)");
    expect(block).toContain("getRuntimeSessionContext(req.nodedcSession)");
    expect(block).toContain("buildAssistantActionProxyCommand");
    expect(block).toContain("requestAiWorkspaceAssistantJson");
    expect(builderBlock).toContain("stripClientAssistantContext");
    expect(builderBlock).toContain('"actorUserId"');
    expect(builderBlock).toContain('"assistantRole"');
    expect(builderBlock).toContain('"groups"');
    expect(builderBlock).toContain('"removesOwnAccess"');
    expect(builderBlock).toContain('"hasAlternativeAdminPath"');
    expect(builderBlock).toContain("resolveAssistantActionOwnerContext");
    expect(builderBlock).toContain("assistantActionRemovesOwnAccess");
    expect(builderBlock).toContain("hasAlternativeAssistantAdminPath");
  });

  it("keeps user profile mutation guarded, idempotent, audited, and scoped", () => {
    const block = sourceBlock('app.patch("/api/admin/users/:userId/profile"', 'app.delete("/api/admin/users/:userId"');

    expect(block).toContain("requireLauncherAdmin");
    expect(block).toContain("assertAdminCanManageUser(req, res, req.params.userId)");
    expect(block).toContain("sendAdminIdempotentJson(req, res");
    expect(block).toContain("controlPlaneStore.updateUserProfile");
    expect(block).toContain('publishControlPlaneEvent("admin.user.updated"');
    expect(block).toContain("scopeAdminMutationResult");
  });

  it("keeps membership mutation guarded, idempotent, audited, and scoped", () => {
    const block = sourceBlock('app.patch("/api/admin/memberships/:membershipId"', 'app.delete("/api/admin/memberships/:membershipId"');

    expect(block).toContain("requireLauncherAdmin");
    expect(block).toContain("assertAdminCanManageMembership(req, res, membership)");
    expect(block).toContain("sendAdminIdempotentJson(req, res");
    expect(block).toContain("controlPlaneStore.updateMembership");
    expect(block).toContain('publishControlPlaneEvent("admin.membership.updated"');
    expect(block).toContain("scopeAdminMutationResult");
  });

  it("keeps hard delete routes outside assistant-ready routes and root-guarded where available", () => {
    const userDeleteBlock = sourceBlock('app.delete("/api/admin/users/:userId"', 'app.post("/api/admin/users/:userId/provision-authentik"');

    expect(userDeleteBlock).toContain("requireRootLauncherAdmin");
    expect(userDeleteBlock).toContain("controlPlaneStore.deleteUser");
  });

  it("keeps admin mutation idempotency conflict and replay behavior", () => {
    expect(source).toContain("sendAdminIdempotentJson");
    expect(source).toContain("idempotency_key_conflict");
    expect(source).toContain('res.setHeader("Idempotency-Replayed", "true")');
    expect(source).toContain("buildAdminMutationFingerprint");
    expect(source).toContain("stableJson(req.body ?? null)");
  });
});
