import assert from "node:assert/strict";
import { test } from "bun:test";

import { createCloudApiServer } from "./server.ts";

test("/auth/session returns structured unauthenticated canonical result", async () => {
  const server = createCloudApiServer({ env: { HWLAB_ACCESS_CONTROL_REQUIRED: "1" } });
  await listen(server);
  try {
    const { port } = server.address() as { port: number };
    const response = await fetch(`http://127.0.0.1:${port}/auth/session`, {
      headers: {
        traceparent: "00-22222222222222222222222222222222-3333333333333333-01",
        "x-request-id": "req_auth_session_diagnostic"
      }
    });
    assert.equal(response.status, 401);
    assert.equal(response.headers.get("x-hwlab-otel-trace-id"), "22222222222222222222222222222222");
    assert.equal(response.headers.get("x-request-id"), "req_auth_session_diagnostic");
    const body = await response.json();
    assert.equal(body.authenticated, false);
    assert.equal(body.authMethod, null);
    assert.equal(body.identityAuthority, null);
    assert.equal(body.sessionKind, null);
    assert.equal(body.actor, null);
    assert.equal(body.valuesRedacted, true);
    assert.equal(body.error.code, "auth_required");
    assert.equal(body.error.diagnostic.traceId, "22222222222222222222222222222222");
    assert.equal(body.error.diagnostic.requestId, "req_auth_session_diagnostic");
    assert.equal(body.error.diagnostic.route, "/auth/session");
    assert.equal(body.error.diagnostic.layer, "api");
    assert.equal(body.error.diagnostic.category, "client");
    assert.equal(body.error.diagnostic.valuesPrinted, false);
    assert.equal(JSON.stringify(body).includes("hwlab_session="), false);
  } finally {
    await close(server);
  }
});

test("/auth/session returns canonical principal for browser user-billing session", async () => {
  const sessionToken = "hws_canonical_session_secret";
  const userBillingClient = {
    configured: true,
    async login(body: any = {}) {
      assert.equal(body.username, "canonical-user");
      return { ok: true, status: 200, body: { token: sessionToken } };
    },
    async introspect(token: string) {
      assert.equal(token, sessionToken);
      return {
        ok: true,
        status: 200,
        body: {
          active: true,
          principal: {
            userId: "usr_canonical_web",
            email: "canonical@hwlab.local",
            username: "canonical-user",
            role: "user",
            status: "active",
            scopes: ["session"],
            authType: "session"
          }
        }
      };
    }
  };
  const server = createCloudApiServer({ env: { HWLAB_ACCESS_CONTROL_REQUIRED: "1" }, userBillingClient });
  await listen(server);
  try {
    const { port } = server.address() as { port: number };
    const login = await fetch(`http://127.0.0.1:${port}/auth/login`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ username: "canonical-user", password: "canonical-password" })
    });
    assert.equal(login.status, 200);
    const cookie = login.headers.get("set-cookie")?.split(";")[0] ?? "";
    assert.match(cookie, /^hwlab_session=hws_/u);
    const loginBody = await login.json();
    assert.equal(loginBody.authMethod, "user-billing-session");
    assert.equal(loginBody.identityAuthority, "user-billing");
    assert.equal(loginBody.sessionKind, "browser");
    assert.equal(loginBody.capabilities.billing, "available");
    assert.equal(JSON.stringify(loginBody).includes(sessionToken), false);

    const response = await fetch(`http://127.0.0.1:${port}/auth/session`, { headers: { cookie } });
    assert.equal(response.status, 200);
    const body = await response.json();
    assert.equal(body.authenticated, true);
    assert.equal(body.authMethod, "user-billing-session");
    assert.equal(body.identityAuthority, "user-billing");
    assert.equal(body.sessionKind, "browser");
    assert.equal(body.actor.id, "usr_canonical_web");
    assert.equal(body.actor.username, "canonical-user");
    assert.equal(body.capabilities.web, "available");
    assert.equal(body.capabilities.workbench, "available");
    assert.equal(body.capabilities.codeAgent, "available");
    assert.equal(body.capabilities.billing, "available");
    assert.equal(body.capabilities.apiKeys, "available");
    assert.equal(body.capabilities.admin, "forbidden");
    assert.equal(body.valuesRedacted, true);
    assert.equal(JSON.stringify(body).includes(sessionToken), false);
  } finally {
    await close(server);
  }
});

test("business billing route consumes authenticated canonical principal instead of re-reading request credential", async () => {
  const delegatedToken = "hws_canonical_delegated_token";
  const userBillingClient = {
    configured: true,
    async billingSummary(token: string, options: any = {}) {
      assert.equal(token, delegatedToken);
      assert.equal(options.limit, 4);
      return { ok: true, status: 200, body: { contractVersion: "user-billing-summary-v1", credits: { balance: 9 }, valuesRedacted: true } };
    }
  };
  const accessController = {
    required: true,
    async authenticate() {
      return {
        ok: true,
        authenticated: true,
        actor: { id: "usr_canonical_consumer", username: "canonical-consumer", role: "user", status: "active" },
        session: { id: "uss_canonical_consumer", userId: "usr_canonical_consumer", tokenSource: "user-billing-session", valuesRedacted: true },
        authMethod: "user-billing-session",
        identityAuthority: "user-billing",
        sessionKind: "browser",
        capabilities: { web: "available", workbench: "available", codeAgent: "available", billing: "available", apiKeys: "available", admin: "forbidden" },
        userBilling: { active: true, token: delegatedToken, principal: { userId: "usr_canonical_consumer", authType: "session" }, valuesRedacted: true },
        valuesRedacted: true
      };
    }
  };
  const server = createCloudApiServer({ env: { HWLAB_ACCESS_CONTROL_REQUIRED: "1" }, accessController, userBillingClient });
  await listen(server);
  try {
    const { port } = server.address() as { port: number };
    const response = await fetch(`http://127.0.0.1:${port}/v1/billing/summary?limit=4`);
    assert.equal(response.status, 200);
    const body = await response.json();
    assert.equal(body.credits.balance, 9);
    assert.equal(body.proxy.source, "hwlab-user-billing");
    assert.equal(JSON.stringify(body).includes(delegatedToken), false);
  } finally {
    await close(server);
  }
});

function listen(server: any) {
  return new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
}

function close(server: any) {
  return new Promise<void>((resolve, reject) => server.close((error: Error | undefined) => (error ? reject(error) : resolve())));
}
