// Phase 5 UI test — scenario: permission-negative
// Test ID: {{testId}}
// Logs in as a role WITHOUT permission, navigates directly to a guarded page,
// expects EITHER an HTTP 403 from the API OR a PermissionGuard fallback rendered.

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

  await page.goto("{{frontendUrl}}{{page}}", { waitUntil: "domcontentloaded" });
  await page.waitForTimeout(1500);

  // Either the API rejected → look for a 403 in network log
  // OR the frontend PermissionGuard intercepted → look for a denied element.
  const got403 = httpRequests.some((r) => r.status === 403);
  let guardRendered = false;
  {{#if expectations.rendersTestId}}
  guardRendered = (await page.locator('[data-testid="{{expectations.rendersTestId}}"]').count()) > 0;
  {{/if}}

  // Worst case: the page LOADED data successfully → permission is broken.
  const got200OnList = httpRequests.some((r) => r.status === 200 && /\/api\//.test(r.url));

  let status = "pass";
  let reason = "ok";
  if (got200OnList && !got403 && !guardRendered) {
    status = "fail";
    reason = "permission negative test FAILED — API returned 200 to a role that should not have access";
  } else if (!got403 && !guardRendered) {
    status = "fail";
    reason = "expected 403 or PermissionGuard fallback, observed neither";
  }

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