import * as NodeWS from "@effect/platform-node/NodeWS";
import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
  const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
  const { ticket } = yield* HttpClient.execute(
    HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
      HttpClientRequest.bearerToken(issued.stdout.trim()),
    ),
  ).pipe(
    Effect.flatMap(HttpClientResponse.filterStatusOk),
    Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
    Effect.provide(FetchHttpClient.layer),
  );
  // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
});

const connect = Effect.fn("scenario.connectLinear")(function* (origin: string) {
  const client = yield* rpcClient(T3_HOME, origin);
  yield* client["issueTrackers.connect"]({ tracker: "linear", token: process.env.LINEAR_API_KEY! });
}, Effect.scoped);

test("Linear filter choices survive an empty search and reload", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Linear filter proof");
  await runPromise(connect(app.baseUrl ?? ""));
  await t3.open("/settings/source-control");
  await screen.getByRole("button", "Toggle Linear details").tap();
  await screen.getByRole("combobox", "Linear team for Linear filter proof").tap();
  await screen.getByRole("option", "T3 Code Factory (T3CF)").tap();
  await t3.open("/issues");
  await screen.getByText("[37971 proof] Filter choice persistence", { exact: true }).waitFor();
  await screen.getByRole("button", "Filters", { exact: true }).tap();
  await screen.getByRole("menuitem", "Labels Any").hover();
  await expect(screen.getByRole("menuitemcheckbox", "docs", { exact: true })).toBeVisible();
  await app.screenshot("initial-labels");
  await browser.keyboard.press("Escape");
  await screen.getByRole("menuitem", "Assignee Anyone").hover();
  await expect(screen.getByRole("menuitemradio", /jmarminge/)).toBeVisible();
  await app.screenshot("initial-assignees");
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  await screen.getByRole("searchbox", "Search issues").fill("no-matches-37971-a1794903888");
  await screen.getByText("Nothing matches that.", { exact: true }).waitFor();
  for (const phase of ["empty-search", "reloaded-empty-search"]) {
    if (phase.startsWith("reloaded")) {
      await browser.reload();
      await screen.getByText("Nothing matches that.", { exact: true }).waitFor();
    }
    await screen.getByRole("button", "Filters", { exact: true }).tap();
    await screen.getByRole("menuitem", "Labels Any").hover();
    await expect.soft(screen.getByRole("menuitemcheckbox", "docs", { exact: true })).toBeVisible();
    await app.screenshot(`${phase}-labels`);
    await browser.keyboard.press("Escape");
    await screen.getByRole("menuitem", "Assignee Anyone").hover();
    await expect.soft(screen.getByRole("menuitemradio", /jmarminge/)).toBeVisible();
    await app.screenshot(`${phase}-assignees`);
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");
  }
});
