import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Hub URLs reject invalid endpoints and Enter cannot save them", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Hub validation demo");
  await t3.open("/settings/providers");
  await screen.getByRole("button", "Add hub", { exact: true }).waitFor();
  await browser.evaluate(() => Array.from(document.querySelectorAll("h3,h2,h4")).find(el => el.textContent === "Usage providers")?.scrollIntoView({ block: "start" }));
  await screen.getByRole("button", "Add hub", { exact: true }).tap();
  const dialog = screen.getByRole("dialog");
  const url = dialog.getByRole("textbox", "Hub URL", { exact: true });
  await dialog.getByLabel("Management key", { exact: true }).fill("secret-key");
  const states: boolean[] = [];
  for (const [label, value] of [
    ["missing-scheme", "hub.example.ts.net:8318"],
    ["not-a-url", "not-a-url"],
    ["ftp-url", "ftp://hub.example.com"],
    ["embedded-credentials", "http://user:pass@hub.example.com"],
  ]) {
    await url.fill(value);
    await app.screenshot(label);
    states.push(await browser.evaluate(() => (document.querySelector('[role="dialog"] button[type="submit"]') as HTMLButtonElement).disabled));
  }
  await url.fill("https://hub.example.ts.net:8318");
  await app.screenshot("valid-https");
  const validEnabled = await browser.evaluate(() => !(document.querySelector('[role="dialog"] button[type="submit"]') as HTMLButtonElement).disabled);
  await dialog.getByLabel("Management key", { exact: true }).fill("");
  await app.screenshot("missing-management-key");
  const missingKeyDisabled = await browser.evaluate(() => (document.querySelector('[role="dialog"] button[type="submit"]') as HTMLButtonElement).disabled);
  await dialog.getByLabel("Management key", { exact: true }).fill("secret-key");
  await url.fill("not-a-url");
  await url.press("Enter");
  await app.screenshot("after-enter-invalid-url");
  const staysOpen = await browser.evaluate(() => document.querySelector('#usage-source-url') !== null);
  expect({ invalidDisabled: states, validEnabled, missingKeyDisabled, staysOpen }).toEqual({ invalidDisabled: [true, true, true, true], validEnabled: true, missingKeyDisabled: true, staysOpen: true });
});
