import { createServer } from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Claude hub accounts sharing an email retain their separate limits after refresh", WEB, async ({ t3, app, screen }) => {
  const accounts = [
    { id: "claude-team.json", auth_index: "t", provider: "claude", email: "same@example.com" },
    { id: "claude-max.json", auth_index: "m", provider: "claude", email: "same@example.com" },
    { id: "claude-pro.json", auth_index: "p", provider: "claude", email: "same@example.com" },
  ];
  let batch = 0;
  const hub = createServer(async (req, res) => {
    res.setHeader("content-type", "application/json");
    if (req.url === "/v0/management/auth-files") {
      batch++;
      res.end(JSON.stringify({ files: accounts }));
      return;
    }
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const body = JSON.parse(raw || "{}");
    const key = body.auth_index;
    const utilization = ({ t: 45, m: 4, p: 70 } as Record<string, number>)[key];
    const payload = body.url?.endsWith("/profile")
      ? { organization: { uuid: `organization-${key}` } }
      : { five_hour: { utilization, resets_at: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString() }, seven_day: { utilization, resets_at: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString() } };
    // Alternate the slowest account so the collapsed bar changes on each refresh.
    const slowest = batch % 2 ? "m" : "t";
    setTimeout(() => res.end(JSON.stringify({ status_code: 200, body: JSON.stringify(payload) })), key === slowest ? 450 : 50);
  });
  await new Promise<void>((resolve) => hub.listen(0, "127.0.0.1", resolve));
  try {
    const address = hub.address();
    if (!address || typeof address === "string") throw new Error("Hub did not bind");
    await t3.project("Limits example");
    await t3.open();
    await screen.getByText("Limits example", { exact: true }).first().waitFor({ state: "visible" });
    await app.open("/settings/providers#usage-providers");
    await screen.getByRole("button", "Add hub", { exact: true }).tap();
    await screen.getByLabel("Hub URL", { exact: true }).fill(`http://127.0.0.1:${address.port}`);
    await screen.getByLabel("Management key", { exact: true }).fill("synthetic-management-key");
    await screen.getByLabel("Label (optional)", { exact: true }).fill("Example hub");
    await screen.getByRole("button", "Add hub", { exact: true }).tap();
    await app.open("/usage");
    await screen.getByRole("button", "Limits", { exact: true }).tap();
    const refresh = screen.getByRole("button", "Refresh limits", { exact: true });
    await screen.getByRole("button", { name: "Refresh limits", exact: true, disabled: false }).waitFor({ state: "visible" });
    await refresh.tap();
    await screen.getByRole("button", { name: "Refresh limits", exact: true, disabled: false }).waitFor({ state: "visible" });
    await screen.getByRole("heading", "Claude", { exact: true }).waitFor({ state: "visible" });
    await app.screenshot("limits-first-refresh");
    await refresh.tap();
    await screen.getByRole("heading", "Claude", { exact: true }).waitFor({ state: "visible" });
    await screen.getByRole("button", { name: "Refresh limits", exact: true, disabled: false }).waitFor({ state: "visible" });
    await app.screenshot("limits-second-refresh");
    await expect(screen.getByRole("button", /SE: 55% left/).first()).toBeVisible();
    await expect(screen.getByRole("button", /SE: 96% left/).first()).toBeVisible();
    await expect(screen.getByRole("button", /SE: 30% left/).first()).toBeVisible();
  } finally {
    await new Promise<void>((resolve, reject) => hub.close((error) => error ? reject(error) : resolve()));
  }
});
