/// <reference lib="dom" />
import { EnvironmentHttpApi, IssueTrackerKind } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

async function linear(query: string, variables: Record<string, unknown>) {
  const response = await fetch("https://api.linear.app/graphql", {
    method: "POST",
    headers: { Authorization: process.env.LINEAR_API_KEY!, "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
  });
  const result = await response.json();
  if (result.errors) throw new Error(JSON.stringify(result.errors));
  return result.data;
}

test("Posting an issue comment returns keyboard focus to the composer", WEB, async ({ t3, app, browser, screen }) => {
  const created = await linear(`mutation($input: IssueCreateInput!) { issueCreate(input: $input) { issue { id identifier } } }`, {
    input: { teamId: process.env.LINEAR_TEST_TEAM_ID, title: `Comment focus proof 47671 ${Date.now()}` },
  });
  const issue = created.issueCreate.issue;
  try {
    await t3.project("comment-focus-proof");
    const projectId = await runPromise(Effect.gen(function* () {
      const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
      const api = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
      const { projects } = yield* api.projects.snapshot({ headers: { authorization: `Bearer ${issued.stdout.trim()}` } });
      const project = projects.find(p => p.title === "comment-focus-proof")!;
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["issueTrackers.connect"]({ tracker: IssueTrackerKind.make("linear"), token: process.env.LINEAR_API_KEY! });
      yield* client["issueTrackers.bindProject"]({ projectId: project.id, binding: { tracker: IssueTrackerKind.make("linear"), scope: process.env.LINEAR_TEST_TEAM_KEY! } });
      return project.id;
    }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)));
    await t3.open(`/issues?${new URLSearchParams({ selectedProjectId: projectId, tracker: "linear", scope: process.env.LINEAR_TEST_TEAM_KEY!, key: issue.identifier })}`);
    const composer = screen.getByRole("textbox", "Add a comment", { exact: true });
    await composer.waitFor({ timeout: 60_000 });
    const outcomes = [];
    for (const [path, body] of [
      ["ctrl-enter", "First comment, sent with Ctrl+Enter."],
      ["tab-enter", "Second comment, sent by tabbing to Comment and pressing Enter."],
    ]) {
      await composer.fill(body);
      if (path === "ctrl-enter") await browser.keyboard.press("Control+Enter");
      else {
        await browser.keyboard.press("Tab");
        await browser.keyboard.press("Enter");
      }
      await screen.getByText(body, { exact: true }).waitFor({ timeout: 60_000 });
      await browser.locator('textarea[aria-label="Add a comment"]:not(:disabled)').waitFor();
      await screen.getByText(body, { exact: true }).waitFor({ timeout: 60_000 });
      await browser.keyboard.type("Next comment");
      outcomes.push(await browser.evaluate(() => ({
        focused: document.activeElement?.getAttribute("aria-label"),
        draft: document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Add a comment"]')!.value,
      })));
      await app.screenshot(`after-${path}`);
    }
    expect(outcomes).toEqual([
      { focused: "Add a comment", draft: "Next comment" },
      { focused: "Add a comment", draft: "Next comment" },
    ]);
  } finally {
    await linear(`mutation($id: String!) { issueDelete(id: $id) { success } }`, { id: issue.id });
  }
});
