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

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

let collector: FixtureCollector

function panelsWithCi(ciPanel: (typeof ALL_PANELS)[number]) {
  return ALL_PANELS.map((panel) => panel.id === 'ci' ? ciPanel : panel)
}

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

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

test('renders fixture map nodes and inspector panel', async ({ page }) => {
  await page.goto('/map')

  await expect(page.getByTestId('map-canvas')).toBeVisible()
  await expect(page.getByRole('button', { name: /laptop/ })).toBeVisible()
  await expect(page.getByRole('button', { name: /GitHub/ })).toBeVisible()
  await expect(page.getByRole('button', { name: /debian1/ })).toBeVisible()
  await expect(page.getByRole('button', { name: /Botmaster/ })).toBeVisible()

  await expect(page.getByTestId('map-inspector')).toBeVisible()
  const inspector = page.getByTestId('map-inspector')
  await expect(inspector.getByText('Agents', { exact: true })).toBeVisible()
  await expect(inspector.getByText('8 (1 orphan)')).toBeVisible()
  await expect(inspector.getByRole('button', { name: 'Reap' })).toBeVisible()
})

test('selecting a node updates the inspector', async ({ page }) => {
  await page.goto('/map')
  await page.getByRole('button', { name: /GitHub/ }).click()
  await expect(page.getByText('alexcodeplace/multideal #4821')).toBeVisible()
})

test('aggregates queue only when every repo queue is complete and non-null', async ({ page }) => {
  await page.goto('/map')
  await expect(page.getByRole('button', { name: /GitHub/ })).toContainText('queue 3')

  await collector.close()
  collector = await startFixtureCollector({
    panels: panelsWithCi(CI_PANEL_HISTORY_INCOMPLETE),
    adapters: ADAPTER_STATUSES,
    items: ALL_ITEMS,
  })
  await page.reload()
  const historyIncomplete = page.getByRole('button', { name: /GitHub/ })
  await expect(historyIncomplete).toContainText('queue 3')
  await expect(historyIncomplete).not.toContainText('#4821')

  for (const incompletePanel of [CI_PANEL_QUEUE_INCOMPLETE, CI_PANEL_QUEUE_NULL]) {
    await collector.close()
    collector = await startFixtureCollector({
      panels: panelsWithCi(incompletePanel),
      adapters: ADAPTER_STATUSES,
      items: ALL_ITEMS,
    })
    await page.reload()
    const github = page.getByRole('button', { name: /GitHub/ })
    await expect(github).toContainText('queue incomplete')
    await expect(github).not.toContainText('queue 1')
  }
})
