/**
 * Tests that the CoT parse-and-store path behaves as when a fake ATAK client sends TAK stream frames.
 * Uses the same framing and payload parsing the server uses; does not start a real TCP server.
 */
import { describe, it, expect, beforeEach } from 'vitest'
import { buildTakFrame, buildPositionCotXml } from '../helpers/fakeAtakClient.js'
import { parseTakStreamFrame, parseCotPayload } from '../../server/utils/cotParser.js'
import { updateFromCot, getActiveEntities, clearCotStore } from '../../server/utils/cotStore.js'

describe('cotServer (parse-and-store path)', () => {
  beforeEach(() => {
    clearCotStore()
  })

  it('stores entity when receiving TAK stream frame with position CoT XML', async () => {
    const xml = buildPositionCotXml({ uid: 'device-1', lat: 37.7, lon: -122.4, callsign: 'Bravo' })
    const frame = buildTakFrame(xml)
    const parsedFrame = parseTakStreamFrame(frame)
    expect(parsedFrame).not.toBeNull()
    const parsed = parseCotPayload(parsedFrame.payload)
    expect(parsed).not.toBeNull()
    expect(parsed.type).toBe('cot')
    await updateFromCot(parsed)
    const active = await getActiveEntities()
    expect(active).toHaveLength(1)
    expect(active[0].id).toBe('device-1')
    expect(active[0].lat).toBe(37.7)
    expect(active[0].lng).toBe(-122.4)
    expect(active[0].label).toBe('Bravo')
  })

  it('updates same uid on multiple messages', async () => {
    const xml1 = buildPositionCotXml({ uid: 'u1', lat: 1, lon: 2 })
    const xml2 = buildPositionCotXml({ uid: 'u1', lat: 3, lon: 4, callsign: 'Updated' })
    const frame1 = buildTakFrame(xml1)
    const frame2 = buildTakFrame(xml2)
    const p1 = parseCotPayload(parseTakStreamFrame(frame1).payload)
    const p2 = parseCotPayload(parseTakStreamFrame(frame2).payload)
    await updateFromCot(p1)
    await updateFromCot(p2)
    const active = await getActiveEntities()
    expect(active).toHaveLength(1)
    expect(active[0].lat).toBe(3)
    expect(active[0].lng).toBe(4)
    expect(active[0].label).toBe('Updated')
  })

  it('infers adsb source from ICAO uid when ingesting CoT position', async () => {
    await updateFromCot({
      id: 'ICAO.abc123',
      lat: 37.7,
      lng: -122.4,
      label: 'N12345',
      eventType: 'a-f-A-C-F',
    })
    const active = await getActiveEntities()
    expect(active[0].source).toBe('adsb')
    expect(active[0].type).toBe('a-f-A-C-F')
  })
})
