// Phase 5 UI test — scenario: detail
// Test ID: {{testId}}
// Loads the list page first, picks the first row's link, navigates to its
// detail page, asserts no 4xx/5xx + expected detail testId renders.

const page = await browser.getPage("main");
const httpRequests = [];
const consoleErrors = [];

page.on("response", (r) => {
  try { httpRequests.push({ url: r.url(), status: r.status(), method: r.request().method() }); } catch (e) {}
});
page.on("console", (m) => {
  try { if (m.type() === "error") consoleErrors.push(m.text()); } catch (e) {}
});

let result;

try {
  console.warn("[ui-test] login as " + "{{user.email}}");
  await page.goto("{{frontendUrl}}/login", { waitUntil: "domcontentloaded" });
  await page.locator('[data-testid="login-email"]').fill("{{user.email}}");
  await page.locator('[data-testid="login-password"]').fill("{{user.password}}");
  await page.locator('[data-testid="login-submit"]').click();
  await page.waitForURL((u) => !u.pathname.endsWith("/login"), { timeout: 10000 });

  // Step 1: navigate to the LIST page, pick first row.
  const listPage = "{{page}}".replace(/\/__detail_id__\/?$/, "");
  console.warn("[ui-test] navigate to list at " + listPage);
  await page.goto("{{frontendUrl}}" + listPage, { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(1500);

  // Find first row's link or use href containing /:id pattern.
  const firstRowLink = page.locator('[data-testid$="-list-row"] a').first();
  const hasRow = await firstRowLink.count() > 0;
  if (!hasRow) {
    result = {
      status: "fail",
      reason: "no detail row available — list is empty (run a create test first)",
      capture: { httpRequests, consoleErrors },
    };
    console.log(JSON.stringify(result));
    return;
  }

  await firstRowLink.click();
  await page.waitForLoadState("domcontentloaded");
  await page.waitForTimeout(1000);

  const bad = httpRequests.find((r) =>
    [400, 401, 403, 404, 500, 502, 503].indexOf(r.status) !== -1,
  );

  let hasExpected = true;
  {{#if expectations.rendersTestId}}
  hasExpected = (await page.locator('[data-testid="{{expectations.rendersTestId}}"]').count()) > 0;
  {{/if}}

  let status = "pass";
  let reason = "ok";
  if (bad) {
    status = "fail";
    reason = "HTTP " + bad.status + " on " + bad.method + " " + bad.url;
  } else if (!hasExpected) {
    status = "fail";
    reason = 'expected testId "{{expectations.rendersTestId}}" not rendered';
  } else if ({{#if expectations.noConsoleError}}consoleErrors.length > 0{{else}}false{{/if}}) {
    status = "fail";
    reason = "console errors: " + consoleErrors[0];
  }

  const screenshotRelPath = "{{captureDir}}/{{testId}}.png";
  try {
    const buf = await page.screenshot({ fullPage: false });
    await saveScreenshot(buf, screenshotRelPath);
  } catch (e) { console.warn("screenshot failed:", e && e.message); }

  result = { status, reason, capture: { httpRequests, consoleErrors, screenshotRelPath } };
} catch (err) {
  result = {
    status: "fail",
    reason: "script-exception: " + (err && err.message ? err.message : String(err)),
    capture: { httpRequests, consoleErrors },
  };
}

console.log(JSON.stringify(result));
