import { test, expect } from '@playwright/test'

test.describe('Authentication', () => {
  test('login with valid credentials redirects to dashboard', async ({ page }) => {
    await page.goto('/login')

    await page.getByLabel('E-Mail').fill('admin@dak-portal.de')
    await page.getByLabel('Passwort').fill('admin123')
    await page.getByRole('button', { name: 'Anmelden' }).click()

    // Should redirect to dashboard after successful login
    await expect(page).toHaveURL(/\/dashboard/)
    await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible()
  })

  test('login with invalid credentials shows error message', async ({ page }) => {
    await page.goto('/login')

    await page.getByLabel('E-Mail').fill('invalid@example.de')
    await page.getByLabel('Passwort').fill('wrongpassword')
    await page.getByRole('button', { name: 'Anmelden' }).click()

    // Should show error alert
    await expect(page.getByText('Ungueltige Anmeldedaten')).toBeVisible()

    // Should remain on login page
    await expect(page).toHaveURL(/\/login/)
  })

  test('protected route redirects to login without auth', async ({ page }) => {
    // Try to access dashboard directly without logging in
    await page.goto('/dashboard')

    // Should be redirected to login page
    await expect(page).toHaveURL(/\/login/)
    await expect(page.getByText('DAK Portal')).toBeVisible()
  })

  test('logout redirects to login', async ({ page }) => {
    // First log in
    await page.goto('/login')
    await page.getByLabel('E-Mail').fill('admin@dak-portal.de')
    await page.getByLabel('Passwort').fill('admin123')
    await page.getByRole('button', { name: 'Anmelden' }).click()
    await expect(page).toHaveURL(/\/dashboard/)

    // Click the logout button in the sidebar/header
    await page.getByRole('button', { name: /abmelden|logout/i }).click()

    // Should be redirected to login page
    await expect(page).toHaveURL(/\/login/)
  })
})
