/// <reference lib="dom" />
import {
  type PullRequestDetail,
  ProjectSnapshot,
  SourceControlProviderKind,
} from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";

import { T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test(
  "Wrapped quoted PR reference labels survive an attachment",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const workspace = await t3.project("Release");
    const origin = app.baseUrl!;
    const environment = await runPromise(environmentId(origin));
    const project = await runPromise(
      Effect.gen(function* () {
        const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
        const { projects } = yield* HttpClient.execute(
          HttpClientRequest.get(`${origin}/api/projects`).pipe(
            HttpClientRequest.bearerToken(issued.stdout.trim()),
          ),
        ).pipe(
          Effect.flatMap(HttpClientResponse.filterStatusOk),
          Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)),
        );
        return projects.find((candidate) => candidate.workspaceRoot === workspace)!;
      }).pipe(Effect.provide(FetchHttpClient.layer)),
    );
    const detail: PullRequestDetail = {
      provider: SourceControlProviderKind.make("github"),
      projectId: project.id,
      projectTitle: project.title,
      workspaceRoot: workspace,
      repository: "scenario/release",
      number: 42,
      title: "Release verification",
      body: "Reference label verification",
      url: "https://github.com/scenario/release/pull/42",
      author: null,
      state: "closed",
      isDraft: false,
      mergeability: "unknown",
      additions: 0,
      deletions: 0,
      changedFiles: 0,
      headBranch: "release",
      baseBranch: "main",
      createdAt: "2026-09-01T00:00:00Z",
      updatedAt: "2026-09-01T00:00:00Z",
      mergedAt: null,
      closedAt: "2026-09-01T00:00:00Z",
      reviewers: [],
      labels: [],
      checks: [],
      mergeCapabilities: { merge: false, squash: false, rebase: false },
      capabilities: {
        edit: { changeRequest: true, comment: false },
        diff: false,
        comment: false,
        search: true,
        actions: [],
        mergeMethods: [],
        review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
        reviewers: { request: false, listCandidates: false },
      },
      viewerPermissions: {
        editChangeRequest: true,
        actions: [],
        comment: false,
        resolve: false,
        verdicts: [],
        requestReviewers: false,
      },
    };
    // Open a previously viewed PR from the saved detail so the scenario needs no forge access.
    const host = new URL(detail.url).host;
    await t3.open();
    await browser.evaluate(
      async ({ environment, host, detailJson }) => {
        const { writePullRequestDetailSnapshot } = await import(
          String("/src/components/pullRequest/pullRequestDetail.logic.ts")
        );
        const detail = JSON.parse(detailJson) as PullRequestDetail;
        writePullRequestDetailSnapshot(localStorage, environment, { ...detail, host }, detail);
        return null;
      },
      { environment, host, detailJson: JSON.stringify(detail) },
    );
    const query = new URLSearchParams({
      repository: detail.repository,
      number: String(detail.number),
      selectedProjectId: project.id,
      selectedEnvironmentId: environment,
      selectedHost: host,
    });
    await t3.open(`/pull-requests?${query}`);

    await screen.getByRole("button", "Comments (0)", { exact: true }).tap();
    await screen.getByRole("button", "Edit description", { exact: true }).tap();
    const body = "> [user\n> guide]: https://example.com/docs\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nSee [the docs][user guide].";
    await screen.getByRole("textbox", "Pull request description", { exact: true }).fill(body);
    await screen.getByRole("button", "Preview", { exact: true }).tap();
    await screen.getByText("See", { exact: false }).waitFor();
    await app.screenshot("wrapped-quoted-reference");
    expect(await screen.getByRole("link", "the docs", { exact: true }).count()).toBe(1);
    await expect(screen.getByRole("link", "the docs", { exact: true })).toHaveAttribute("href", "https://example.com/docs");
  },
);
