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

function formInputs(page: import('@playwright/test').Page) {
  const dialog = page.locator('.t-dialog:visible')
  return {
    id: dialog.locator('input[placeholder="例如: openai"]'),
    name: dialog.locator('input[placeholder="例如: OpenAI"]'),
    apiKey: dialog.locator('input[placeholder="sk-..."]'),
    baseUrl: dialog.locator('input[placeholder="例如: https://api.openai.com/v1"]'),
    saveBtn: dialog.locator('.t-dialog__footer').getByRole('button', { name: '保存' }),
    cancelBtn: dialog.locator('.t-dialog__footer').getByRole('button', { name: '取消' }),
  }
}

test.describe('供应商表单验证', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/providers')
    await expect(page.getByRole('heading', { name: '供应商管理' })).toBeVisible()
  })

  test('应显示必填字段验证', async ({ page }) => {
    await page.getByRole('button', { name: '添加供应商' }).click()
    await expect(page.locator('.t-dialog:visible')).toBeVisible()

    await formInputs(page).saveBtn.click()

    await expect(page.getByText('请输入供应商 ID')).toBeVisible()
    await expect(page.getByText('请输入名称')).toBeVisible()
    await expect(page.getByText('请输入 API Key')).toBeVisible()
    await expect(page.getByText('请输入 Base URL')).toBeVisible()
  })

  test('应验证URL格式', async ({ page }) => {
    await page.getByRole('button', { name: '添加供应商' }).click()
    await expect(page.locator('.t-dialog:visible')).toBeVisible()

    const inputs = formInputs(page)
    await inputs.id.fill('test_url')
    await inputs.name.fill('Test')
    await inputs.apiKey.fill('sk_test')
    await inputs.baseUrl.fill('not-a-url')

    await inputs.saveBtn.click()
    await expect(page.getByText('请输入有效的 URL')).toBeVisible()
  })

  test('取消后表单应重置', async ({ page }) => {
    await page.getByRole('button', { name: '添加供应商' }).click()
    await expect(page.locator('.t-dialog:visible')).toBeVisible()

    let inputs = formInputs(page)
    await inputs.id.fill('should_be_reset')
    await inputs.name.fill('Should Be Reset')

    await inputs.cancelBtn.click()
    await expect(page.locator('.t-dialog:visible')).not.toBeVisible()

    await page.getByRole('button', { name: '添加供应商' }).click()
    await expect(page.locator('.t-dialog:visible')).toBeVisible()

    inputs = formInputs(page)
    await expect(inputs.id).toHaveValue('')
    await expect(inputs.name).toHaveValue('')
  })

  test('快速连续点击只打开一个对话框', async ({ page }) => {
    await page.getByRole('button', { name: '添加供应商' }).click()
    await expect(page.locator('.t-dialog:visible')).toBeVisible()

    expect(await page.locator('.t-dialog:visible').count()).toBe(1)

    await formInputs(page).cancelBtn.click()
    await expect(page.locator('.t-dialog:visible')).not.toBeVisible()
  })
})
