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

const stamp = Date.now();
const applicant = {
  name: `Test User ${stamp}`,
  email: `test+${stamp}@example.com`,
  password: "supersecretpw123",
  country: "United Kingdom",
  institution: "Test General Hospital",
  professionalRole: "consultant",
  motivationText:
    "I want to collaborate on shoulder research with the OrthoGlobe network.",
};

test("apply then admin approves then applicant logs in", async ({ page, browser }) => {
  // 1. Applicant submits join application
  await page.goto("/join");
  await page.getByLabel("Full name").fill(applicant.name);
  await page.getByLabel("Email").fill(applicant.email);
  await page.getByLabel("Password (min 12 characters)").fill(applicant.password);
  await page.getByLabel("Country").selectOption(applicant.country);
  await page.getByLabel("Institution / hospital").fill(applicant.institution);
  await page.getByLabel("Role").selectOption(applicant.professionalRole);
  await page
    .getByLabel("Why do you want to join? (max 200 characters)")
    .fill(applicant.motivationText);

  await page.getByRole("button", { name: /Submit application/i }).click();
  await expect(page).toHaveURL(/\/join\/submitted/);

  // 2. Admin signs in (isolated context) and approves
  const adminContext = await browser.newContext();
  const adminPage = await adminContext.newPage();
  await adminPage.goto("/login");
  await adminPage.getByLabel("Email").fill("atef@orthoglobe.org");
  await adminPage
    .getByLabel("Password")
    .fill(process.env.SEED_ADMIN_PASSWORD ?? "changeme-after-first-login");
  await adminPage.getByRole("button", { name: /Sign in/i }).click();
  await expect(adminPage).toHaveURL(/\/account/);

  await adminPage.goto("/admin/applications");
  // Find the row for this applicant by email and click its Review link
  const row = adminPage.locator("tr", { hasText: applicant.email });
  await row.getByRole("link", { name: "Review" }).click();
  await expect(adminPage).toHaveURL(/\/admin\/applications\/[^/]+$/);

  await adminPage.getByRole("button", { name: /^Approve$/ }).click();
  await expect(adminPage).toHaveURL(/\/admin\/applications$/);

  await adminContext.close();

  // 3. Applicant signs in and lands on /account
  await page.goto("/login");
  await page.getByLabel("Email").fill(applicant.email);
  await page.getByLabel("Password").fill(applicant.password);
  await page.getByRole("button", { name: /Sign in/i }).click();
  await expect(page).toHaveURL(/\/account/);
  await expect(
    page.getByRole("heading", {
      name: new RegExp(`Welcome, ${applicant.name}`),
    })
  ).toBeVisible();
});
