// Phase 5 UI test — scenario: edit
// Test ID: {{testId}}
// Loads list, picks first row, opens edit, modifies a fixture field,
// submits, expects 200/204.

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) {}
});

const fixture = {{{fixtureJson}}};

let result;

try {
  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 });

  // The page template contains "/__detail_id__/edit". Strip the placeholder
  // and find the first row to edit instead.
  const editPath = "{{page}}";
  const listPath = editPath.replace(/\/__detail_id__\/edit\/?$/, "");
  await page.goto("{{frontendUrl}}" + listPath, { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(1500);

  const editLink = page.locator('[data-testid$="-list-row"] [data-testid="row-edit"]').first();
  const hasEdit = await editLink.count() > 0;
  if (!hasEdit) {
    result = {
      status: "fail",
      reason: "no edit affordance on list — missing data-testid=row-edit (run create first)",
      capture: { httpRequests, consoleErrors },
    };
    console.log(JSON.stringify(result));
    return;
  }
  await editLink.click();
  await page.waitForLoadState("domcontentloaded");
  await page.waitForTimeout(1000);

  // Modify each fixture field. We APPEND a marker so the edit is unique.
  for (const key of Object.keys(fixture)) {
    const selector = '[data-testid="form-field-' + key + '"]';
    const loc = page.locator(selector);
    if (await loc.count() === 0) continue;
    const current = await loc.inputValue().catch(() => "");
    await loc.fill(current + " (edited)");
  }

  const beforeSubmit = httpRequests.length;
  await page.locator('[data-testid="form-submit"]').click();
  await page.waitForTimeout(2500);

  const submitResp = httpRequests.slice(beforeSubmit).find((r) => r.method === "PUT" || r.method === "PATCH" || r.method === "POST");
  const expected = [{{#each expectations.httpStatus}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}];

  let status = "pass";
  let reason = "ok";
  if (!submitResp) {
    status = "fail";
    reason = "no PUT/PATCH/POST after submit";
  } else if (expected.indexOf(submitResp.status) === -1) {
    status = "fail";
    reason = "edit submit returned HTTP " + submitResp.status + ", expected one of [" + expected.join(",") + "]";
  }

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

  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));
