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

export const ACCOUNTS = {
  superAdmin: { email: "dean@occp.local", password: "OccpDemo2026!" },
  deanAdmin: { email: "admin@occp.local", password: "OccpDemo2026!" },
  encoder: { email: "encoder@occp.local", password: "OccpDemo2026!" },
  viewer: { email: "viewer@occp.local", password: "OccpDemo2026!" },
} as const;

export async function signIn(page: Page, account: { email: string; password: string }) {
  await page.goto("/login");
  await page.getByLabel("Email address").fill(account.email);
  await page.getByLabel("Password").fill(account.password);
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("heading", { name: "Dashboard", level: 1 })).toBeVisible();
}

/**
 * Resolves a student's detail URL from the student list.
 *
 * The search term goes in the URL rather than through the debounced search box,
 * so the helper cannot race the client-side filter. The live search box and tab
 * navigation each have their own dedicated tests; helpers navigate directly so
 * that a test failure points at the behaviour under test rather than at an
 * incidental hydration race.
 */
export async function findStudentUrl(page: Page, studentNumber: string): Promise<string> {
  await page.goto(`/students?q=${encodeURIComponent(studentNumber)}`);
  const link = page.getByRole("link", { name: studentNumber, exact: true });
  await expect(link).toBeVisible();
  const href = await link.getAttribute("href");
  expect(href, `no detail link found for student ${studentNumber}`).toBeTruthy();
  return href!;
}

/** Opens a student's profile tab. Returns the student's base URL. */
export async function openStudent(page: Page, studentNumber: string): Promise<string> {
  const url = await findStudentUrl(page, studentNumber);
  await page.goto(url);
  await expect(page.getByRole("navigation", { name: "Student sections" })).toBeVisible();
  return url;
}

/** Opens a student's curriculum assessment screen. */
export async function openStudentAssessment(page: Page, studentNumber: string): Promise<string> {
  const url = await findStudentUrl(page, studentNumber);
  await page.goto(`${url}/assessment`);
  return url;
}
