/// <reference lib="dom" />
import { expect } from "e2e";
import { ProjectSnapshot, PullRequestDetail, SourceControlProviderKind } from "@t3tools/contracts";
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("Pull request markdown editors follow prose direction", WEB, async ({ t3, app, browser, screen }) => {
  const workspace = await t3.project("Demo");
  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 response = 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 response.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: 48233, title: "Fix RTL editors", body: "Description", url: "https://github.com/pingdotgg/t3code/pull/48233",
    author: null, state: "open", isDraft: false, mergeability: "unknown", additions: 1, deletions: 1, changedFiles: 1,
    headBranch: "fix/rtl-pr-editors", baseBranch: "main", createdAt: "2026-09-01T00:00:00Z", updatedAt: "2026-09-01T00:00:00Z", mergedAt: null, closedAt: null,
    reviewers: [], labels: [], checks: [], mergeCapabilities: { merge: false, squash: false, rebase: false },
    capabilities: { diff: false, comment: true, search: true, actions: [], mergeMethods: [], review: { inlineComment: false, reply: false, resolve: false, verdicts: ["approve", "request_changes", "comment"] }, reviewers: { request: false, listCandidates: false } },
    viewerPermissions: { actions: [], resolve: false, comment: true, verdicts: ["approve", "request_changes", "comment"], requestReviewers: false },
  };
  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 parsed = JSON.parse(detailJson) as PullRequestDetail;
    writePullRequestDetailSnapshot(localStorage, environment, { ...parsed, host }, parsed);
  }, { 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.getByText(detail.title, { exact: true }).first().waitFor({ timeout: 60_000 });
  const commentButton = screen.getByRole("button", "Comment on pull request");
  await commentButton.click();
  const comment = browser.locator('textarea[aria-label="Comment on this pull request"]');
  await comment.fill("Review בבקשה בדוק את התיקון לפני המיזוג.");
  await expect.poll(() => browser.evaluate(() => getComputedStyle(document.querySelector('textarea[aria-label="Comment on this pull request"]')!).direction)).toBe("rtl");
  await app.screenshot("rtl-comment-editor");
  const reviewTab = screen.getByRole("button", "Review");
  await reviewTab.click();
  const review = browser.locator('textarea[aria-label="Review summary"]');
  await review.fill("Looks good، يرجى مراجعة هذا التغيير قبل الدمج.");
  await expect.poll(() => browser.evaluate(() => getComputedStyle(document.querySelector('textarea[aria-label="Review summary"]')!).direction)).toBe("rtl");
  await app.screenshot("rtl-review-editor");
});
