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

export async function gotoInbox(page: Page) {
  await page.goto("/mail/inbox")
  await expect(page.locator("[data-email-row-id]").first()).toBeVisible()
}

export function composeWindow(page: Page): Locator {
  return page.locator("[data-compose-window]").last()
}

export async function openCompose(page: Page) {
  const composeButton = page
    .getByRole("button", { name: "Nouveau message" })
    .first()
  await composeButton.click()
  await expect(composeWindow(page)).toBeVisible()
}

export async function fillCompose(
  page: Page,
  {
    to,
    subject,
    body,
  }: {
    to: string
    subject: string
    body: string
  }
) {
  const compose = composeWindow(page)
  const toField = compose.locator('input[type="text"]').first()

  await toField.fill(to)
  await toField.press("Enter")

  await compose.getByPlaceholder("Objet").fill(subject)
  await compose.locator(".ProseMirror").click()
  await compose.locator(".ProseMirror").fill(body)
}

export async function sendComposeNow(page: Page) {
  const compose = composeWindow(page)
  await compose.getByRole("button", { name: "Envoyer", exact: true }).click()
  await page.getByRole("button", { name: "Envoyer maintenant" }).click()
  await expect(page.getByText("Message envoyé")).toBeVisible()
  await expect(compose).toHaveCount(0)
}

export async function scheduleComposeInOneHour(page: Page) {
  const compose = composeWindow(page)
  await compose.locator("button.rounded-r-full").click()
  await page.getByRole("menuitem", { name: "Envoyer dans une heure" }).click()
  await expect(page.getByText(/Ce mail sera envoyé le/)).toBeVisible()
}
