import { expect, test } from '@playwright/test'
import { startFixtureCollector, type FixtureCollector } from './fixture-collector'
import { ADAPTER_STATUSES, ALL_ITEMS, ALL_PANELS } from './fixtures/collector-fixtures'

test.describe.configure({ mode: 'serial' })

let collector: FixtureCollector

test.beforeAll(async () => {
  collector = await startFixtureCollector({ panels: ALL_PANELS, adapters: ADAPTER_STATUSES, items: ALL_ITEMS })
})

test.afterAll(async () => {
  await collector.close()
})

test('allowlisted action POST without Origin header returns 403 (CSRF default-deny)', async ({ request }) => {
  const res = await request.post('/api/collector/actions/reap', {
    data: { args: { pid: '88231' }, requestedBy: 'orphan-agent' },
  })
  expect(res.status()).toBe(403)
})

test('non-allowlisted action verb returns 404 through the proxy', async ({ request, baseURL }) => {
  const res = await request.post('/api/collector/actions/kill', {
    headers: { origin: new URL(baseURL!).origin },
    data: { args: { pid: '88231' }, requestedBy: 'orphan-agent' },
  })
  expect(res.status()).toBe(404)
})

test('reap with pid absent from orphan candidates returns 400 through the proxy', async ({ request, baseURL }) => {
  const res = await request.post('/api/collector/actions/reap', {
    headers: { origin: new URL(baseURL!).origin },
    data: { args: { pid: '99999' }, requestedBy: 'orphan-agent' },
  })
  expect(res.status()).toBe(400)
})

test('reap confirm dialog posts to the mock executor and shows a success toast', async ({ page }) => {
  await page.goto('/inbox')

  const row = page.locator('[data-inbox-item-id="orphan-agent"]')
  await row.getByRole('button', { name: 'Reap' }).click()
  await expect(page.locator('[data-action-confirm]')).toBeVisible()

  await page.locator('[data-action-confirm-submit]').click()
  const toast = page.locator('[role="status"][aria-live="polite"]')
  await expect(toast).toContainText('Reap succeeded')
  await expect(toast).toContainText('mock executor ok')

  expect(collector.actionCalls.at(-1)).toEqual({
    verb: 'reap',
    body: {
      args: { pid: '88231' },
      requestedBy: 'orphan-agent',
    },
  })
})
