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

async function signInAsAdmin(page: Page) {
  await page.goto("/auth/signin");
  await page.fill('input[type="email"]', "admin@capakraken.dev");
  await page.fill('input[type="password"]', "admin123");
  await page.click('button[type="submit"]');
  await expect(page).toHaveURL(/\/(dashboard|resources)/);
}

test.describe("Holiday Calendar Editor", () => {
  test("creates a city calendar, previews a holiday, blocks duplicates and confirms deletion", async ({ page }) => {
    const suffix = Date.now().toString();
    const calendarName = `E2E City Calendar ${suffix}`;
    const holidayName = `E2E Local Holiday ${suffix}`;

    await signInAsAdmin(page);
    await page.goto("/admin/vacations");

    await expect(page.getByTestId("holiday-calendar-editor")).toBeVisible();

    await page.getByTestId("holiday-calendar-name-input").fill(calendarName);
    await page.getByTestId("holiday-calendar-scope-select").selectOption("CITY");
    await page.getByTestId("holiday-calendar-country-select").selectOption({ label: "Germany (DE)" });
    await page.getByTestId("holiday-calendar-city-select").selectOption({ label: "Muenchen" });
    await page.getByTestId("holiday-calendar-create-button").click();

    await expect(page.getByTestId(/holiday-calendar-row-/).filter({ hasText: calendarName }).first()).toBeVisible();
    await expect(page.getByRole("heading", { name: calendarName })).toBeVisible();
    await expect(page.getByTestId("holiday-entry-create-button")).toBeVisible();

    await page.getByTestId("holiday-entry-date-input").fill("2026-08-08");
    await page.getByTestId("holiday-entry-name-input").fill(holidayName);
    await page.getByTestId("holiday-entry-source-input").fill("E2E");
    await page.getByTestId("holiday-entry-create-button").click();

    await expect(page.getByText(holidayName).first()).toBeVisible();

    await page.getByTestId("holiday-preview-year-input").fill("2026");
    await expect(page.getByTestId("holiday-preview-table")).toContainText(holidayName);
    await expect(page.getByTestId("holiday-preview-table")).toContainText("2026-08-08");

    await page.getByTestId("holiday-entry-date-input").fill("2026-08-08");
    await page.getByTestId("holiday-entry-name-input").fill(`${holidayName} Duplicate`);
    await page.getByTestId("holiday-entry-create-button").click();

    await expect(page.getByText("A holiday entry for this calendar and date already exists")).toBeVisible();

    page.once("dialog", (dialog) => dialog.accept());
    await page.getByTestId(/holiday-entry-delete-/).first().click();
    await expect(page.getByText(holidayName).first()).not.toBeVisible();

    page.once("dialog", (dialog) => dialog.accept());
    await page.getByTestId("holiday-calendar-delete-button").click();
    await expect(page.getByRole("heading", { name: calendarName })).not.toBeVisible();
  });
});
