// Phase 5 UI test — scenario: form-submit
// Test ID: {{testId}}
// Logs in, navigates to the create form, fills fixture fields, submits,
// expects 200/201 + redirect to detail page.

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

  console.warn("[ui-test] navigate to create form: {{page}}");
  await page.goto("{{frontendUrl}}{{page}}", { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(1000);

  // Fill each fixture field by data-testid="form-field-<key>".
  for (const key of Object.keys(fixture)) {
    const value = fixture[key];
    const selector = '[data-testid="form-field-' + key + '"]';
    const locator = page.locator(selector);
    const count = await locator.count();
    if (count === 0) {
      console.warn("missing form field selector: " + selector);
      continue;
    }
    await locator.fill(String(value));
  }

  // Reset httpRequests so we only assert on the submit-triggered ones.
  const beforeSubmit = httpRequests.length;
  await page.locator('[data-testid="form-submit"]').click();
  await page.waitForTimeout(2500);

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

  let status = "pass";
  let reason = "ok";
  if (!submitResp) {
    status = "fail";
    reason = "no POST/PUT detected after submit (form did not fire)";
  } else if (expected.indexOf(submitResp.status) === -1) {
    status = "fail";
    reason = "submit returned HTTP " + submitResp.status + " on " + submitResp.url + ", expected one of [" + expected.join(",") + "]";
  } 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) {}

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