/// <reference lib="dom" />
import { expect } from "e2e";
import { startSecondServer, SECOND_HOME } from "./second-server.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test("Thread destinations explain unavailable connections and preserve local work", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Thread link proof");
  const existing = await t3.thread({ project, title: "Listed thread control", messages: ["Local conversation control"] });
  await t3.open(existing);
  await screen.getByRole("textbox").waitFor();
  await screen.getByText("Syncing messages…", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("listed-thread-control");
  await screen.getByRole("button", "New thread", {exact: true}).tap();
  await screen.getByRole("textbox").fill("Preserved unsent draft");
  const draftUrl = await browser.url();
  await app.screenshot("draft-before-navigation");
  const results: boolean[] = [];
  const unavailable = async (label: string, path: string) => {
    await t3.open(path);
    try { await expect(screen.getByText("Thread unavailable", {exact:true})).toBeVisible(); results.push(true); }
    catch { results.push(false); }
    await app.screenshot(label);
  };
  const missingThread = "thread:project:11111111-2222-4333-8444-555555555555:66666666-7777-4888-8999-aaaaaaaaaaaa";
  await unavailable("unknown-environment-direct-link", `/9e0d4c3a-2222-4b5c-8d6e-000000000099/${encodeURIComponent(missingThread)}`);
  if (results.at(-1)) {
    await screen.getByRole("link", "Open Environments", {exact: true}).tap();
    await screen.getByRole("button", "Add environment", {exact:true}).waitFor();
    await app.screenshot("unknown-link-settings-recovery");
  }
  await t3.open(new URL(draftUrl).pathname);
  await screen.getByRole("textbox").waitFor();
  await app.screenshot("draft-after-navigation");
  results.push((await browser.evaluate(() => document.querySelector('[contenteditable="true"]')?.textContent ?? "")).includes("Preserved unsent draft"));
  await t3.open(existing);
  await screen.getByRole("textbox").waitFor();
  await screen.getByText("Syncing messages…", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("listed-thread-after-navigation");
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const {host, token} = await server.ready;
    const remoteId = await runPromise(environmentId(host));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment", {exact:true}).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", {exact:true}).tap();
    await screen.getByRole("button", "List", {exact:true}).tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor();
    await app.screenshot("configured-environment-before-disable");
    await screen.getByRole("switch", "Switch off Scenario", {exact:true}).tap();
    await app.screenshot("configured-environment-disabled");
    await screen.getByRole("switch", "Switch on Scenario", {exact:true}).waitFor();
    await unavailable("disabled-environment-thread-link", `/${remoteId}/${encodeURIComponent(missingThread)}`);
    await t3.open("/settings/connections");
    await screen.getByRole("button", "List", {exact:true}).tap();
    const descriptor = await (await fetch(`${host}/.well-known/t3/environment`)).json();
    await browser.route(`${host}/.well-known/t3/environment`, route => route.fulfill({json: {...descriptor, orchestrationProtocolVersion: 9999}}));
    await screen.getByRole("switch", "Switch on Scenario", {exact:true}).tap();
    await screen.getByText(/· Client not supported$/).waitFor();
    await app.screenshot("configured-environment-unsupported");
    await unavailable("unsupported-environment-thread-link", `/${remoteId}/${encodeURIComponent(missingThread)}`);
  } finally { await server.stop(); }
  await expect(results).toEqual([true, true, true, true]);
});
