import { test, expect } from "@playwright/test";

async function loginViaUi(page, username, password) {
  await page.goto("/login");
  await page.locator("#username").fill(username);
  await page.locator("#password").fill(password);
  await Promise.all([
    page.waitForURL((url) => !url.pathname.endsWith("/login"), {
      timeout: 15_000,
    }),
    page.locator('form button[type="submit"]').click(),
  ]);
}

test("/meetings loads the schedule directly", async ({ page }) => {
  await page.addInitScript(() => {
    try {
      window.localStorage.setItem("tx-lang", "en");
    } catch {
      /* ignore */
    }
  });
  await loginViaUi(page, "admin", "admin123");
  await page.goto("/meetings");
  await expect(page).toHaveURL(/\/meetings(?:\?|#|$)/);
  await expect(page.getByTestId("em-edit-mode-toggle")).toBeVisible();
});

test("/executive-meetings redirects to /meetings (back-compat for old links)", async ({
  page,
}) => {
  await page.addInitScript(() => {
    try {
      window.localStorage.setItem("tx-lang", "en");
    } catch {
      /* ignore */
    }
  });
  await loginViaUi(page, "admin", "admin123");
  await page.goto("/executive-meetings?date=2025-01-15#schedule");
  await expect(page).toHaveURL(/\/meetings\?date=2025-01-15#schedule$/);
  await expect(page.getByTestId("em-edit-mode-toggle")).toBeVisible();
});

test("the apps list returns the new /meetings route for the executive-meetings slug", async ({
  page,
  request,
}) => {
  // Home tile launches via openApp(app) which navigates to app.route
  // straight from the API. Hitting the apps API directly proves the
  // seed migration ran and the home grid will follow automatically.
  await page.addInitScript(() => {
    try {
      window.localStorage.setItem("tx-lang", "en");
    } catch {
      /* ignore */
    }
  });
  await loginViaUi(page, "admin", "admin123");
  const cookies = await page.context().cookies();
  const cookieHeader = cookies
    .map((c) => `${c.name}=${c.value}`)
    .join("; ");
  const res = await request.get("/api/apps", {
    headers: { Cookie: cookieHeader },
  });
  expect(res.ok()).toBeTruthy();
  const apps = await res.json();
  const meetings = apps.find((a) => a.slug === "executive-meetings");
  expect(meetings).toBeTruthy();
  expect(meetings.route).toBe("/meetings");
});
