import { test, expect } from "@playwright/test"
import {
  E2E_INVITE_TOKEN,
  E2E_MIGRATEE_EMAIL,
  expectClaimAuthenticatedStep,
  gotoClaimPage,
  gotoMigrationPage,
  installMigrationApiMocks,
  mockAuthSession,
  submitClaim,
} from "./helpers/migration-onboarding"

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => {
    window.localStorage.clear()
    window.sessionStorage.clear()
  })
})

test.describe("onboarding migration (mocked API)", () => {
  test("claim page rejects invite link without token", async ({ page }) => {
    await page.goto("/onboard/claim")
    await expect(page.getByRole("heading", { name: "Lien d'invitation invalide" })).toBeVisible()
  })

  test("claim page prompts login when session is missing", async ({ page }) => {
    await mockAuthSession(page, { authenticated: false })
    await installMigrationApiMocks(page)
    await gotoClaimPage(page)

    await expect(page.getByRole("heading", { name: "Revendiquer votre compte" })).toBeVisible()
    await expect(page.getByText(E2E_MIGRATEE_EMAIL)).toBeVisible()
    await expect(page.getByRole("link", { name: "Se connecter pour continuer" })).toBeVisible()
    await expect(page.getByRole("button", { name: "Revendiquer mon compte" })).toHaveCount(0)
  })

  test("claim then migration journey for oauth google project", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "draft",
      authMode: "oauth",
      sourceProvider: "google",
    })
    await gotoClaimPage(page)
    await expectClaimAuthenticatedStep(page)
    await submitClaim(page)

    await expect(page.getByRole("heading", { name: "Migration en cours" })).toBeVisible()
    await expect(
      page.getByText(/Votre administrateur doit activer le projet de migration/)
    ).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Google" })).toHaveCount(0)
    await expect(page.getByRole("button", { name: "Autoriser Microsoft" })).toHaveCount(0)
  })

  test("migration shows oauth when project is active", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "active",
      inviteStatus: "claimed",
      authMode: "oauth",
      sourceProvider: "google",
    })
    await gotoMigrationPage(page)

    await expect(page.getByText(/Étape suivante : autorisez l'accès/)).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Google" })).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Microsoft" })).toHaveCount(0)
  })

  test("migration hides oauth for google domain-wide delegation", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "active",
      inviteStatus: "claimed",
      authMode: "google_dwd",
      sourceProvider: "google",
    })
    await gotoMigrationPage(page)

    await expect(
      page.getByText(/Aucune autorisation OAuth personnelle requise/)
    ).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Google" })).toHaveCount(0)
    await expect(page.getByRole("button", { name: "Autoriser Microsoft" })).toHaveCount(0)
  })

  test("migration shows microsoft admin consent warning", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "active",
      inviteStatus: "claimed",
      sourceProvider: "microsoft",
    })
    await gotoMigrationPage(page)

    await expect(page.getByText(/consentement admin/)).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Microsoft" })).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Google" })).toHaveCount(0)
  })

  test("migration hides oauth after credentials are stored", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "active",
      inviteStatus: "claimed",
      hasMigrationCredentials: true,
      jobs: [
        { service: "mail", status: "running", stats_json: { imported: 12, estimated_total: 100 } },
        { service: "contacts", status: "pending", stats_json: { imported: 0 } },
        { service: "calendar", status: "pending", stats_json: { imported: 0 } },
        { service: "drive", status: "pending", stats_json: { imported: 0 } },
      ],
    })
    await gotoMigrationPage(page)

    await expect(page.getByText(/Autorisation enregistrée/)).toBeVisible()
    await expect(page.getByRole("button", { name: "Autoriser Google" })).toHaveCount(0)
    await expect(page.getByText("12 éléments importés")).toBeVisible()
  })

  test("migration shows oauth success banner from redirect", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "active",
      inviteStatus: "claimed",
      hasMigrationCredentials: true,
    })
    await page.goto(
      `/onboard/migration?token=${encodeURIComponent(E2E_INVITE_TOKEN)}&oauth=success`
    )

    await expect(page.getByText(/Autorisation enregistrée. L'import démarre/)).toBeVisible()
  })

  test("claimed invite redirects claim page to migration", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "active",
      inviteStatus: "claimed",
    })
    await gotoClaimPage(page)

    await expect(page).toHaveURL(new RegExp(`/onboard/migration\\?token=${E2E_INVITE_TOKEN}`))
    await expect(page.getByRole("heading", { name: "Migration en cours" })).toBeVisible()
  })

  test("unclaimed user on migration page returns to claim", async ({ page }) => {
    await mockAuthSession(page)
    await installMigrationApiMocks(page, {
      projectStatus: "draft",
      inviteStatus: "invited",
    })
    await gotoMigrationPage(page)

    await expect(page).toHaveURL(new RegExp(`/onboard/claim\\?token=${E2E_INVITE_TOKEN}`))
  })
})
