/** E2E-PUSH-002 — push submit ends submitting state quickly */
import { test, expect } from '../fixtures.mjs'
import { login, nav } from '../helpers.mjs'

const mockServer = {
  id: 9001,
  name: 'e2e-push-mock',
  domain: '10.0.0.1',
  target_path: '/var/www',
  category: null,
  is_online: true,
  status: 'online',
}

test('E2E-PUSH-002 submitting clears after accepted response', async ({ page }) => {
  await page.route('**/api/servers**', async (route) => {
    if (route.request().method() !== 'GET') {
      await route.continue()
      return
    }
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({
        items: [mockServer],
        total: 1,
        page: 1,
        per_page: 200,
        pages: 1,
      }),
    })
  })
  await page.route('**/api/sync/validate-source-path', async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({
        valid: true,
        path: '/tmp/nexus-e2e-src',
        file_count: 1,
        size_bytes: 100,
      }),
    })
  })
  await page.route('**/api/sync/files**', async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({
        accepted: true,
        batch_id: 'aabbccddeeff',
        total: 1,
        completed: 0,
        failed: 0,
        cancelled: 0,
        results: {},
      }),
    })
  })

  await login(page)
  await nav(page, '/push')

  await page.getByPlaceholder('/path/to/files').fill('/tmp/nexus-e2e-src')
  await page.getByRole('button', { name: '验证路径' }).click()
  await expect(page.getByText('e2e-push-mock')).toBeVisible({ timeout: 20000 })
  await page.getByText('e2e-push-mock', { exact: true }).click()

  const pushBtn = page.getByRole('button', { name: '推送', exact: true })
  const postDone = page.waitForResponse(
    (r) => r.request().method() === 'POST' && r.url().includes('/sync/files'),
    { timeout: 20000 },
  )
  await pushBtn.click()
  const res = await postDone
  expect(res.status()).toBe(200)
  const body = await res.json()
  expect(body.accepted).toBe(true)
})
