import { test, expect } from '@playwright/test'
import { TEST_USER, clearAuth } from './helpers'

test.describe('Login flow', () => {
  test.beforeEach(async ({ page }) => {
    // Ensure no stale tokens from a previous test
    await page.goto('/login')
    await clearAuth(page)
  })

  test('should login successfully with valid credentials', async ({ page }) => {
    await page.goto('/login')

    // Fill in the form
    await page.getByPlaceholder('请输入用户名').fill(TEST_USER.username)
    await page.getByPlaceholder('请输入密码').fill(TEST_USER.password)

    // Submit
    await page.getByRole('button', { name: /登\s*录/ }).click()

    // Should redirect to /agent (which redirects to /agent/chat)
    await expect(page).toHaveURL(/\/agent/)

    // The login logo should no longer be visible
    await expect(page.locator('.login-logo')).not.toBeVisible()
  })

  test('should show error for wrong password', async ({ page }) => {
    await page.goto('/login')

    await page.getByPlaceholder('请输入用户名').fill(TEST_USER.username)
    await page.getByPlaceholder('请输入密码').fill('definitely-wrong-password-12345')

    await page.getByRole('button', { name: /登\s*录/ }).click()

    // The LoginView shows an a-alert with type="error" containing the
    // server's error message ("Invalid username or password").
    const errorAlert = page.locator('.ant-alert-error')
    await expect(errorAlert).toBeVisible({ timeout: 10_000 })

    // Should still be on the login page
    await expect(page).toHaveURL(/\/login/)

    // The error message should mention invalid credentials
    const alertText = await errorAlert.textContent()
    expect(alertText?.toLowerCase()).toMatch(/invalid|无效|错误|incorrect|失败/)
  })

  test('should redirect unauthenticated users to login', async ({ page }) => {
    // Clear any existing auth state, then try to visit a protected route
    await clearAuth(page)

    await page.goto('/agent/chat')

    // The router guard should redirect to /login?redirect=/agent/chat
    await expect(page).toHaveURL(/\/login/)
    await expect(page).toHaveURL(/redirect=/)

    // The login form should be visible
    await expect(page.getByPlaceholder('请输入用户名')).toBeVisible()
    await expect(page.getByPlaceholder('请输入密码')).toBeVisible()
  })

  test('should redirect to original page after login', async ({ page }) => {
    await clearAuth(page)

    // Visit a protected route — should redirect to login with redirect param
    await page.goto('/agent/chat')
    await expect(page).toHaveURL(/\/login\?redirect=/)

    // Now log in
    await page.getByPlaceholder('请输入用户名').fill(TEST_USER.username)
    await page.getByPlaceholder('请输入密码').fill(TEST_USER.password)
    await page.getByRole('button', { name: /登\s*录/ }).click()

    // Should be redirected back to the originally requested page
    await expect(page).toHaveURL(/\/agent\/chat/)
  })
})
