/// <reference lib="dom" />
import { expect } from "e2e";
import { ProjectSnapshot } 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 { run } from "./shell.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test("Fetched GitLab comment stays on the space-padded filename", WEB, async ({ t3, app, browser, screen }) => {
  const workspace = await t3.project("Inline comments");
  await runPromise(run("git", ["remote", "add", "origin", "https://gitlab.com/julius54/t3-inline-space-proof-46500.git"], {cwd:workspace}));
  await runPromise(run("git", ["fetch", "origin", "main", "feature"], {cwd:workspace}));
  await runPromise(run("git", ["checkout", "-B", "feature", "origin/feature"], {cwd:workspace}));
  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(p=>p.workspaceRoot===workspace)!;
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const query=new URLSearchParams({repository:"julius54/t3-inline-space-proof-46500",number:"1",selectedProjectId:project.id,selectedEnvironmentId:environment,selectedHost:"gitlab.com"});
  await t3.open(`/pull-requests?${query}`);
  await screen.getByText("Comment on line 2 of the space-padded file", {exact:true}).waitFor();
  await screen.getByRole("button","Code",{exact:true}).tap();
  await screen.getByRole("button","Expand all files",{exact:true}).tap();
  await screen.getByRole("button", "Open · 1 comment", {exact:true}).waitFor();
  await screen.getByRole("button", /Open #1 Change line 2/).waitFor();
  await app.screenshot("inline-comment-exact-file");
  const text=await browser.evaluate(()=>{
    return [...document.querySelectorAll('diffs-container')]
      .filter(el => el.textContent?.includes('Comment on line 2 of the space-padded file'))
      .map(el => el.shadowRoot?.textContent ?? '').join('\n');
  });
  expect(text.includes('line two CHANGED')).toBe(true);
});
