import { test, expect } from '@playwright/test'
import { loginAndHydrate, forceRelogin } from './helpers'

test.describe('Terminal panel', () => {
  test.beforeEach(async ({ page }) => {
    await loginAndHydrate(page)
    // The terminal view lives at /legacy/terminal (the /terminal route
    // redirects there — see router/index.ts).
    await page.goto('/legacy/terminal')
    // Cold-start race: the router guard awaits startupCheck() (whoami with
    // the persisted refresh token). On a fresh browser context the guard
    // may bounce to /login AFTER the initial URL has settled on
    // /legacy/terminal — so checking page.url() alone is unreliable.
    // Wait for either .terminal-panel (success) OR the login button
    // (cold-start failure) to render, then retry once on failure.
    const loginBtn = page.getByRole('button', { name: /登\s*录/ })
    const terminalPanel = page.locator('.terminal-panel')
    await expect
      .poll(
        async () =>
          (await terminalPanel.count()) > 0 || (await loginBtn.count()) > 0,
        { timeout: 20_000, intervals: [500, 1_000, 2_000] },
      )
      .toBe(true)
    if ((await loginBtn.count()) > 0) {
      // Cold-start failed — force a fresh login (bypassing the module-level
      // token cache, which may have been invalidated by a previous spec
      // corrupting the refresh token) and retry once.
      await forceRelogin()
      await loginAndHydrate(page)
      await page.goto('/legacy/terminal')
      await expect(terminalPanel).toBeVisible({ timeout: 20_000 })
    }
  })

  test('should display the terminal panel with mode tabs', async ({ page }) => {
    // The TerminalPanel component renders .terminal-panel
    const terminalPanel = page.locator('.terminal-panel')
    await expect(terminalPanel).toBeVisible({ timeout: 10_000 })

    // The "本地终端" (local terminal) tab should always be visible
    await expect(
      terminalPanel.getByRole('button', { name: /本地终端/ }),
    ).toBeVisible()

    // The connection status indicator should be present
    await expect(terminalPanel.locator('.terminal-panel__indicator')).toBeVisible()
  })

  test('should show server terminal tab for admin users', async ({ page }) => {
    // The test user is an admin, so the "服务端终端" tab should be visible
    // (it's gated behind authStore.canUseServerTerminal()).
    const terminalPanel = page.locator('.terminal-panel')
    await expect(terminalPanel).toBeVisible({ timeout: 10_000 })

    await expect(
      terminalPanel.getByRole('button', { name: /服务端终端/ }),
    ).toBeVisible()
  })

  test('should open the whitelist manager drawer', async ({ page }) => {
    // Wait for the terminal view to mount
    await expect(page.locator('.terminal-panel')).toBeVisible({ timeout: 10_000 })

    // The whitelist button is positioned in the top-right corner of the
    // terminal view (SafetyOutlined icon inside .terminal-view__whitelist-btn).
    const whitelistBtn = page.locator('.terminal-view__whitelist-btn')
    await expect(whitelistBtn).toBeVisible()
    await whitelistBtn.click()

    // The drawer should open and contain the WhitelistManager component.
    // The drawer title is "终端白名单管理".
    const drawer = page.locator('.ant-drawer-content')
    await expect(drawer).toBeVisible({ timeout: 5_000 })

    // The WhitelistManager renders an a-tabs with "我的白名单" tab
    await expect(page.getByRole('tab', { name: '我的白名单' })).toBeVisible()

    // The "添加" button and the input for new patterns should be visible.
    // Use regex to match possible Ant Design Vue auto-inserted space.
    await expect(
      drawer.getByPlaceholder('输入命令模式，如: git, npm, ls'),
    ).toBeVisible()
    await expect(drawer.getByRole('button', { name: /添\s*加/ })).toBeVisible()
  })

  test('should display admin-only tabs in whitelist manager', async ({ page }) => {
    // Open the whitelist drawer
    await expect(page.locator('.terminal-panel')).toBeVisible({ timeout: 10_000 })
    await page.locator('.terminal-view__whitelist-btn').click()

    const drawer = page.locator('.ant-drawer-content')
    await expect(drawer).toBeVisible({ timeout: 5_000 })

    // Admin users should see the "全局白名单", "黑名单", and "审计日志" tabs
    await expect(page.getByRole('tab', { name: '全局白名单' })).toBeVisible()
    await expect(page.getByRole('tab', { name: '黑名单' })).toBeVisible()
    await expect(page.getByRole('tab', { name: '审计日志' })).toBeVisible()
  })
})
