import { CommandId, EnvironmentHttpApi } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { run } from "./shell.ts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Nested-project diff opens the file when the repository ends in a space", WEB, async ({ t3, app, browser, screen }) => {
  const original = await t3.project("fixture");
  const repository = `/tmp/factory-pr-48637-evidence-1/run-${Date.now()}/repo `;
  const project = `${repository}/sub`;
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(project, { recursive: true });
    const git = (...args: string[]) => run("git", args, { cwd: repository });
    yield* git("init", "--initial-branch=main");
    yield* fs.writeFileString(`${project}/file.txt`, "one\n");
    yield* git("add", "sub/file.txt");
    yield* git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Baseline");
    yield* fs.writeFileString(`${project}/file.txt`, "two\n");
    const { stdout } = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const headers = { authorization: `Bearer ${stdout.trim()}` };
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
    const { projects } = yield* client.projects.snapshot({ headers });
    const entry = projects.find(({ workspaceRoot }) => workspaceRoot === original);
    if (!entry) throw new Error("Scenario project not registered");
    yield* client.projects.mutate({ headers, payload: {
      type: "project.update", commandId: CommandId.make(`nest-${entry.id}`), projectId: entry.id,
      workspaceRoot: project,
    }});
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const thread = await t3.thread({ project, title: "Open nested diff file", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", /Uncommitted/).tap();
  await browser.locator("[data-title]").filter({ hasText: "sub/file.txt" }).click();
  try {
    await expect(screen.getByText("two", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("opened-nested-diff-file");
  }
});
