import { createServer } from "node:http";
import { networkInterfaces } from "node:os";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A quota source shared by environments appears once", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("quota-demo");
  const address = Object.values(networkInterfaces()).flat().find((a) => a?.family === "IPv4" && !a.internal)?.address;
  if (!address) throw new Error("A non-loopback IPv4 address is required");
  const mock = createServer((request, response) => {
    response.setHeader("Content-Type", "application/json");
    if (request.url === "/quota") {
      response.end(JSON.stringify({version: 1, accounts: [{id: "team", label: "Team gateway", windows: [
        {id: "5h", kind: "session", label: "5 hours", usedPercent: 42},
        {id: "weekly", kind: "weekly", label: "Weekly", usedPercent: 17},
      ]}]}));
    } else if (request.url === "/hub/v0/management/auth-files") {
      response.end(JSON.stringify({files: [{id: "broken", auth_index: "broken", provider: "claude", email: "broken@example.com"}]}));
    } else if (request.url === "/hub/v0/management/api-call") {
      response.end(JSON.stringify({status_code: 500, body: "{}"}));
    } else { response.statusCode = 404; response.end("{}"); }
  });
  await new Promise<void>((resolve) => mock.listen(0, "0.0.0.0", resolve));
  const port = (mock.address() as {port: number}).port;
  const sources = {
    gateway: {kind: "http", label: "Gateway", managementKey: "", url: `http://${address}:${port}/quota`, enabled: true},
    hub: {kind: "cliproxy", label: "Hub", url: `http://${address}:${port}/hub`, managementKey: "synthetic-test-key", enabled: true},
  };
  const configure = (home: string, origin: string) => runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    yield* client["server.updateSettings"]({patch: {usageLimitSources: sources}});
  })));
  const second = startSecondServer(app.baseUrl ?? "");
  try {
    const {host, token} = await second.ready;
    await configure(T3_HOME, app.baseUrl ?? "");
    await configure(SECOND_HOME, host);
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("dialog", {name: "Backend added"}).waitFor();
    await app.open("/settings/connections");
    await screen.getByRole("button", "List", {exact: true}).tap();
    await screen.getByRole("button", "More actions for Scenario").last().tap();
    await screen.getByRole("menuitem", "Rename…").tap();
    await browser.locator("#environment-label").fill("Desktop");
    await screen.getByRole("button", "Save", {exact: true}).tap();
    await app.open("/usage");
    await screen.getByRole("heading", "Team gateway", {exact: true}).first().waitFor();
    await screen.getByText(/broken@example.com.*HTTP 500/).first().waitFor();
    await screen.getByRole("button", "Refresh limits").waitFor();
    await app.screenshot("shared-quota-source-and-failed-account");
    const actual = await browser.evaluate(() => ({
      cards: [...document.querySelectorAll("h3")].filter((e) => e.textContent === "Team gateway").length,
      notices: [...document.querySelectorAll('[data-slot="alert-title"]')].filter((e) => e.textContent?.includes("broken@example.com")).length,
    }));
    expect(actual).toEqual({cards: 1, notices: 1});
  } finally {
    await second.stop();
    await new Promise<void>((resolve, reject) => mock.close((error) => error ? reject(error) : resolve()));
  }
});
