import { describe, expect, it } from 'vitest';
import type { TrackPlaybackResponse } from '../../api/types';
import { buildTrackRailSelection, formatDuration, sampledEventIndex, trackAddressCoordinate, trackCsv, trackPlaybackInterval } from './track';

describe('track domain', () => {
  it('formats durations and maps original event indices to sampled points', () => {
    expect(formatDuration(3671)).toBe('01:01:11');
    expect(sampledEventIndex({ index: 50 } as never, 11, 101)).toBe(5);
    expect(sampledEventIndex({ index: 50, sampledIndex: 7 } as never, 11, 101)).toBe(7);
  });

  it('precomputes sparse rail highlights and bounds the playback cadence', () => {
    const playback = {
      points: Array.from({ length: 8 }, (_, index) => ({ longitude: index, latitude: index })),
      stops: [{ sampledIndex: 3 }],
      events: [{ index: 50 }, { index: 75, sampledIndex: 6 }],
      summary: { pointCount: 101 }
    } as TrackPlaybackResponse;
    const selection = buildTrackRailSelection(playback);

    expect(selection.stopIndexesByPoint[1]).toBeUndefined();
    expect(selection.stopIndexesByPoint[2]).toEqual([0]);
    expect(selection.stopIndexesByPoint[3]).toEqual([0]);
    expect(selection.stopIndexesByPoint[4]).toEqual([0]);
    expect(selection.eventIndexesByPoint[4]).toEqual([0]);
    expect(selection.eventIndexesByPoint[6]).toEqual([1]);
    expect(trackPlaybackInterval(1)).toBe(300);
    expect(trackPlaybackInterval(4)).toBe(75);
    expect(trackPlaybackInterval(100)).toBe(55);
  });

  it('exports the current result with UTF-8 BOM and escaped values', () => {
    const track = {
      plate: '粤A,001', vin: 'VIN', summary: { startTime: '2026-07-03 10:00:00' },
      points: [{ vin: 'VIN', plate: '粤A,001', protocol: 'JT808', deviceTime: '2026-07-03 10:00:00', serverTime: '2026-07-03 10:00:01', longitude: 113.1, latitude: 23.1, speedKmh: 10, totalMileageKm: 100 }]
    } as TrackPlaybackResponse;
    const csv = trackCsv(track);
    expect(csv.startsWith('\uFEFFVIN,')).toBe(true);
    expect(csv).toContain('"粤A,001"');
  });

  it('coalesces GPS jitter into street-level address cells and rejects invalid coordinates', () => {
    expect(trackAddressCoordinate(113.123441, 23.123441)).toEqual({ longitude: 113.1234, latitude: 23.1234, key: '113.1234,23.1234' });
    expect(trackAddressCoordinate(113.123449, 23.123449)?.key).toBe('113.1234,23.1234');
    expect(trackAddressCoordinate(0, 0)).toBeUndefined();
    expect(trackAddressCoordinate(181, 23)).toBeUndefined();
  });
});
