/* WITNESS · owner-unreachable-settings
 *
 * WHY THIS WALK EXISTS
 * --------------------
 * Three owner settings pages answer HTTP 200 and render: /owner/settings/payments/,
 * /owner/settings/pos/, /owner/settings/dietary/. The question a person would ask is not
 * "does the URL work" - it is "can I GET THERE?" App-Doc's own 3-pass rule says a capability
 * that isn't reachable in the UI is not a capability.
 *
 * THE ORACLE IS EXHAUSTIVE ENUMERATION, NOT A FAILED GUESS.
 * "I couldn't find a link" is worthless - I might have looked in the wrong place. So on each
 * screen I enumerate EVERY <a href> and every clickable nav item in the DOM and test the
 * whole set against the target path. A link found anywhere ends the finding immediately.
 *
 * NO MUTATION. Menus are opened and closed; nothing is saved.
 */
import { test } from "@playwright/test";
import { journal, look, signInOwner, account, closeRole, deskContext, OWNER, DWELL }
  from "../lib-witness.mjs";
import fs from "node:fs";

const RID = JSON.parse(fs.readFileSync("/workspace/uat/runs/wave0/fixtures.json","utf8"))["canary-mosaic"];
const TARGETS = ["/owner/settings/payments", "/owner/settings/pos", "/owner/settings/dietary"];
const SCREENS = [["the dashboard","/owner/dashboard/"], ["Food Items","/owner/food-items/"],
                 ["the Menu page","/owner/menu/"], ["Tables/Staff","/owner/experience/"],
                 ["Personalize","/owner/personalize/"], ["my restaurants","/owner/restaurants/"]];

/** Every href on the page, plus whatever opening the user menu and the mobile nav reveals. */
async function allLinks(page) {
  for (const sel of ['[data-testid="user-menu-trigger"]','[data-testid="mobile-nav-open"]']) {
    await page.locator(sel).first().click({ timeout: 4000 }).catch(() => {});
    await page.waitForTimeout(900);
  }
  return page.evaluate(() => [...document.querySelectorAll("a[href]")]
    .map(a => a.getAttribute("href")).filter(Boolean));
}

test("owner-unreachable-settings", async ({ browser }) => {
  const jr = journal("owner-unreachable-settings");
  jr.target({ app: "owner", url: OWNER, restaurantId: RID, fixture: "canary-mosaic" });
  jr.note("_Three settings pages render perfectly well if you already know the address. "
        + "This walk asks whether an owner who does not know the address can ever get to them._");
  jr.note("**No mutation:** menus opened and closed, nothing saved.");

  const ctx = await deskContext(browser, jr, "owner");
  const page = await ctx.newPage();
  const seen = new Set();
  let verdict = "INCOMPLETE", why = "";

  try {
    await jr.step("OWNER", "I sign in as the owner", async id => {
      const a = account("canaryOwner");
      await signInOwner(page, a.email, a.password, RID);
      const t = await look(page, jr, "owner", id, "signed in");
      if (/incorrect/i.test(t.slice(0,300))) throw new Error("I could not sign in.");
      return t.slice(0, 160);
    });

    await jr.step("OWNER", "The pages themselves work if I type the address", async id => {
      const rows = [];
      for (const p of TARGETS) {
        const res = await page.goto(`${OWNER}${p}/?restaurantId=${RID}`, { waitUntil: "domcontentloaded" });
        await page.waitForTimeout(DWELL);
        const main = await page.evaluate(() =>
          (document.querySelector("main")||document.body).innerText.replace(/\s+/g," ").trim());
        rows.push(`\`${p}\` -> **${res ? res.status() : "?"}**, reads _"${main.slice(0,90)}"_`);
      }
      await look(page, jr, "owner", id, "typed straight in");
      jr.note("> **Typing the address:**\n>\n> - " + rows.join("\n> - "));
      return `All three answer and render: ${rows.length} page(s).`;
    });

    await jr.step("OWNER", "Now I go looking for them the way an owner would", async id => {
      for (const [name, path] of SCREENS) {
        await page.goto(`${OWNER}${path}?restaurantId=${RID}`, { waitUntil: "domcontentloaded" });
        await page.waitForTimeout(DWELL);
        for (const h of await allLinks(page)) seen.add(h);
        await look(page, jr, "owner", id, `looking on ${name}`);
      }
      const hits = TARGETS.filter(t => [...seen].some(h => h.includes(t)));
      jr.note(`> **I enumerated every link on ${SCREENS.length} screens** — sidebar, user menu `
            + `and mobile nav opened on each — and collected **${seen.size}** distinct hrefs.`);
      if (hits.length)
        return `They ARE reachable: found link(s) to ${hits.join(", ")}. No finding here.`;
      const settingsish = [...seen].filter(h => /setting/i.test(h));
      return `Not one of the ${seen.size} links points at any of them. The only settings-ish `
           + `href anywhere is: ${settingsish.length ? settingsish.join(", ") : "none at all"}.`;
    });

    await jr.step("OWNER", "And the settings index an owner would guess at", async id => {
      const res = await page.goto(`${OWNER}/owner/settings/?restaurantId=${RID}`,
                                  { waitUntil: "domcontentloaded" });
      await page.waitForTimeout(DWELL);
      const t = await look(page, jr, "owner", id, "the settings index");
      const st = res ? res.status() : null;
      return `\`/owner/settings/\` answers **${st}**. Screen: ${t.slice(0,140)}`;
    });

    verdict = "WALKED"; why = "Enumerated every link on six owner screens against three routes.";
  } catch (e) {
    verdict = "STOPPED"; why = String(e.message||e).split("\n")[0].slice(0,300); throw e;
  } finally { jr.finish(verdict, why); await closeRole(ctx, jr, "owner"); }
});
