import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

async function link(target: string, path: string) {
  await symlink(target, path).catch((error) => {
    if (error.code !== "EEXIST") throw error;
  });
}

test("Add project browses directory symlinks and autocompletes their paths", WEB, async ({ t3, app, screen }) => {
  await t3.project("Demo");
  const fixture = "/tmp/factory-pr-40830-evidence-3";
  const links = join(fixture, "links");
  await mkdir(join(links, "real-dir", "project"), { recursive: true });
  await writeFile(join(fixture, "file.txt"), "Synthetic fixture\n");
  await link("real-dir", join(links, "personal"));
  await link("../file.txt", join(links, "file-link"));
  await link("missing", join(links, "broken-link"));
  await t3.open();
  await screen.getByRole("button", "Add project").tap();
  await screen.getByText("Local folder", { exact: true }).tap();
  const input = screen.getByRole("combobox");
  await input.fill(`${links}/`);
  await screen.getByText("real-dir", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("parent-listing");
  await input.fill(`${links}/per`);
  await screen.getByText("real-dir", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("prefix-autocomplete");
  await input.fill(`${links}/personal/`);
  await screen.getByText("project", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("symlink-children");
  await expect(screen.getByText("project", { exact: true })).toBeVisible();
  await input.fill(`${links}/`);
  await screen.getByText("real-dir", { exact: true }).waitFor({ state: "visible" });
  await expect(screen.getByText("personal", { exact: true })).toBeVisible();
  await expect(screen.getByText("file-link", { exact: true })).not.toBeVisible();
  await expect(screen.getByText("broken-link", { exact: true })).not.toBeVisible();
  await input.fill(`${links}/per`);
  await expect(screen.getByText("personal", { exact: true })).toBeVisible();
});
