import { readFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Forgejo opens newest comments and retains a posted reply", WEB, async ({t3, app, browser, screen}) => {
  const token = readFileSync(process.env.PROOF_TOKEN_FILE!, "utf8").trim();
  const api = async (path: string, method = "GET", body?: unknown) => {
    const response = await fetch(`http://localhost:3300/api/v1/${path}`, {method, headers:{Authorization:`token ${token}`, "Content-Type":"application/json"}, ...(body === undefined ? {} : {body:JSON.stringify(body)})});
    if (!response.ok) throw new Error(`Forgejo ${method} ${path}: ${response.status}`);
    return response.status === 204 ? null : response.json();
  };
  const repo = `comments-${Date.now()}`;
  await api("user/repos", "POST", {name:repo, auto_init:true});
  const issuePath = `repos/scenario/${repo}/issues/1`;
  try {
    await api(`repos/scenario/${repo}/issues`, "POST", {title:"Issue with 51 comments", body:"Newest replies should be visible on opening and after posting."});
    for (let n=1;n<=51;n++) {
      await api(`${issuePath}/comments`,"POST",{body:`comment ${n}`});
      // Forgejo timestamps have one-second precision; give each seeded reply its own time.
      await new Promise(resolve => setTimeout(resolve, 1050));
    }
    const project = await t3.project("forgejo-comments");
    execFileSync("git", ["remote","add","origin",`http://localhost:3300/scenario/${repo}.git`], {cwd:project});
    const thread = await t3.thread({project,title:"Forgejo comments",messages:["Start"]});
    await t3.open(thread);
    await app.open("/issues");
    await screen.getByText("Issue with 51 comments", {exact:true}).tap();
    await screen.getByText("Activity (51)", {exact:true}).waitFor();
    const bodies = () => browser.evaluate(() => Array.from(document.querySelectorAll("article")).map(a=>a.textContent ?? "").filter(t=>/comment \d+/.test(t)).map(t=>Number(t.match(/comment (\d+)/)![1])));
    const showEnd = () => browser.evaluate(() => {document.querySelectorAll("article").item(document.querySelectorAll("article").length-1)?.scrollIntoView({block:"center"}); return null;});
    await showEnd();
    await app.screenshot("01-open-latest-reply");
    const opened = await bodies();
    await screen.getByRole("button", "Load older comments", {exact:true}).tap();
    await screen.getByText("comment 1",{exact:true}).waitFor();
    await showEnd();
    await app.screenshot("02-loaded-older");
    const loaded = await bodies();
    await screen.getByPlaceholder("Leave a comment").fill("comment 52");
    await screen.getByRole("button", "Comment", {exact:true}).tap();
    await screen.getByText("Activity (52)", {exact:true}).waitFor();
    await showEnd();
    await app.screenshot("03-posted-reply");
    const posted = await bodies();
    await app.open("/issues");
    await screen.getByText("Issue with 51 comments", {exact:true}).tap();
    await screen.getByText("Activity (52)", {exact:true}).waitFor();
    await showEnd();
    await app.screenshot("04-reopened-latest-reply");
    const reopened = await bodies();
    expect({opened, loaded, posted, reopened}).toEqual({opened:Array.from({length:50},(_,i)=>i+2),loaded:Array.from({length:51},(_,i)=>i+1),posted:Array.from({length:50},(_,i)=>i+3),reopened:Array.from({length:50},(_,i)=>i+3)});
  } finally { await api(`repos/scenario/${repo}`, "DELETE"); }
});
