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

test.describe("Authentication", () => {
  test("redirects unauthenticated user to login", async ({ page }) => {
    await page.goto("/dashboard");
    await expect(page).toHaveURL(/\/login/);
  });

  test("shows login form elements", async ({ page }) => {
    await page.goto("/login");
    await expect(page.getByLabel("Email address")).toBeVisible();
    await expect(page.getByLabel("Password")).toBeVisible();
    await expect(page.getByRole("button", { name: /sign in/i })).toBeVisible();
  });

  test("shows error on invalid credentials", async ({ page }) => {
    await page.goto("/login");
    await page.getByLabel("Email address").fill("wrong@example.com");
    await page.getByLabel("Password").fill("wrongpassword");
    await page.getByRole("button", { name: /sign in/i }).click();
    await expect(page.getByText(/invalid email or password/i)).toBeVisible();
  });

  test("logs in successfully and redirects to dashboard", async ({ page }) => {
    await page.goto("/login");
    await page.getByLabel("Email address").fill("tech@pelagia.local");
    await page.getByLabel("Password").fill("tech1234");
    await page.getByRole("button", { name: /sign in/i }).click();
    await expect(page).toHaveURL(/\/dashboard/);
    await expect(page.getByText("Dashboard")).toBeVisible();
  });

  test("manager sees approvals in navigation", async ({ page }) => {
    await page.goto("/login");
    await page.getByLabel("Email address").fill("manager@pelagia.local");
    await page.getByLabel("Password").fill("manager1234");
    await page.getByRole("button", { name: /sign in/i }).click();
    await expect(page).toHaveURL(/\/dashboard/);
    await expect(page.getByRole("link", { name: /approvals/i })).toBeVisible();
  });

  test("signs out and returns to login", async ({ page }) => {
    await page.goto("/login");
    await page.getByLabel("Email address").fill("tech@pelagia.local");
    await page.getByLabel("Password").fill("tech1234");
    await page.getByRole("button", { name: /sign in/i }).click();
    await page.getByTitle("Sign out").click();
    await expect(page).toHaveURL(/\/login/);
  });
});
