// Phase 5 UI test — scenario: delete
// Test ID: {{testId}}
// Loads list, finds the first row's delete affordance, confirms, expects 204/200.

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

  const listPath = "{{page}}".replace(/\/__detail_id__\/?$/, "");
  await page.goto("{{frontendUrl}}" + listPath, { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(1500);

  const deleteBtn = page.locator('[data-testid$="-list-row"] [data-testid="row-delete"]').first();
  const hasDelete = await deleteBtn.count() > 0;
  if (!hasDelete) {
    result = {
      status: "fail",
      reason: "no delete affordance on list — missing data-testid=row-delete",
      capture: { httpRequests, consoleErrors },
    };
    console.log(JSON.stringify(result));
    return;
  }

  // Some apps confirm via a dialog/modal. Auto-accept any browser confirm.
  page.on("dialog", (d) => { try { d.accept(); } catch (e) {} });

  const beforeDelete = httpRequests.length;
  await deleteBtn.click();
  await page.waitForTimeout(500);

  // If a confirm modal exists, click its data-testid="confirm-delete" affordance.
  const confirmBtn = page.locator('[data-testid="confirm-delete"]');
  if (await confirmBtn.count() > 0) {
    await confirmBtn.click();
  }
  await page.waitForTimeout(2000);

  const deleteResp = httpRequests.slice(beforeDelete).find((r) => r.method === "DELETE");
  const expected = [{{#each expectations.httpStatus}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}];

  let status = "pass";
  let reason = "ok";
  if (!deleteResp) {
    status = "fail";
    reason = "no DELETE request fired";
  } else if (expected.indexOf(deleteResp.status) === -1) {
    status = "fail";
    reason = "delete returned HTTP " + deleteResp.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));
