import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { http } from 'msw'
import { server } from '../../../../tests/msw/server'
import { jsonResponse } from '../../../../tests/msw/helpers'
import { renderWithProviders, screen, waitFor, userEvent } from '../../../../tests/helpers/render'
import { seedBearer, clearBearer } from '../../../../tests/helpers/auth'
import { seedAircraft } from '../../../../tests/fixtures/seed_aircraft'
import { AdminPage } from '..'

// v2 admin — Default Aircrafts panel: render 6 mockup rows + star toggle.

beforeEach(() => {
  seedBearer()
  server.use(
    http.get('/api/flights/aircrafts', () => jsonResponse(seedAircraft)),
  )
})
afterEach(() => {
  clearBearer()
})

describe('AdminPage — Default Aircrafts', () => {
  it('renders all 6 seeded aircraft with id · resolution · minutes', async () => {
    renderWithProviders(<AdminPage />)
    expect(await screen.findByText('DJI Mavic 3')).toBeInTheDocument()
    expect(screen.getByText('Matrice 300 RTK')).toBeInTheDocument()
    expect(screen.getByText('Leleka-100')).toBeInTheDocument()
    expect(screen.getByText('Fixed Wing Scout')).toBeInTheDocument()
    expect(screen.getByText('Autel EVO II Pro')).toBeInTheDocument()
    expect(screen.getByText('PD-2 Recon')).toBeInTheDocument()
    // Subline format: "AC-001 · 4K · 46MIN"
    expect(screen.getByText(/AC-001\s+·\s+4K\s+·\s+46MIN/)).toBeInTheDocument()
  })

  it('star toggle PATCHes isDefault and updates UI', async () => {
    const calls: { id: string; body: unknown }[] = []
    server.use(
      http.patch('/api/flights/aircrafts/:id', async ({ params, request }) => {
        const body = await request.json()
        calls.push({ id: String(params.id), body })
        return jsonResponse({ ok: true })
      }),
    )
    renderWithProviders(<AdminPage />)
    await screen.findByText('DJI Mavic 3')

    // AC-002 starts non-default → click its star to mark default.
    const ac002Row = screen.getByText('Matrice 300 RTK').closest('[data-aircraft-id]') as HTMLElement
    expect(ac002Row).not.toBeNull()
    // Within the row find the toggle button (set-default label).
    const toggleBtn = ac002Row.querySelector('button[aria-pressed="false"]') as HTMLButtonElement
    expect(toggleBtn).not.toBeNull()
    await userEvent.click(toggleBtn)

    await waitFor(() => expect(calls.length).toBe(1))
    expect(calls[0].id).toBe('AC-002')
    expect((calls[0].body as { isDefault: boolean }).isDefault).toBe(true)
  })
})
