import { describe, expect, it } from 'vitest';
import { buildHistoryChartSeries, buildHistorySeriesPanels, formatExportFileSize, formatHistoryValue, HISTORY_EXPORT_POLL_MS, historyExportPollInterval, parseHistoryKeywords } from './history';

describe('history domain', () => {
  it('parses and bounds multi-vehicle input', () => {
    expect(parseHistoryKeywords('粤A1, 粤A1;VIN2\nVIN3')).toEqual(['粤A1', 'VIN2', 'VIN3']);
    expect(parseHistoryKeywords('1,2,3,4,5,6')).toHaveLength(5);
  });

  it('formats units without fabricating missing values', () => {
    expect(formatHistoryValue(undefined)).toBe('—');
    expect(formatHistoryValue(42.5, { unit: 'km/h' } as never)).toBe('42.5 km/h');
  });

  it('builds only numeric series with at least two evidence points', () => {
    const rows = [
      { values: { speedKmh: 20 }, deviceTime: '2' },
      { values: { speedKmh: 10 }, deviceTime: '1' }
    ] as never;
    const series = buildHistoryChartSeries(rows, [{ key: 'speedKmh', label: '速度', unit: 'km/h' }] as never);
    expect(series).toHaveLength(1);
    expect(series[0].path).toContain('M');
  });

  it('builds unit-separated server aggregate panels and breaks lines across missing buckets', () => {
    const response = {
      dateFrom: '2026-07-13T16:00:00Z', dateTo: '2026-07-13T17:00:00Z',
      summary: { grainSeconds: 60 },
      series: [
        { vin: 'VIN1', plate: '粤A1', protocol: 'GB32960', metric: 'speedKmh', label: '速度', unit: 'km/h', points: [{ time: '2026-07-13T16:00:00Z', value: 10 }, { time: '2026-07-13T16:01:00Z', value: 20 }, { time: '2026-07-13T16:10:00Z', value: 30 }] },
        { vin: 'VIN1', plate: '粤A1', protocol: 'GB32960', metric: 'totalMileageKm', label: '总里程', unit: 'km', points: [{ time: '2026-07-13T16:00:00Z', value: 100 }, { time: '2026-07-13T16:01:00Z', value: 101 }] }
      ]
    } as never;
    const panels = buildHistorySeriesPanels(response);
    expect(panels.map((panel) => panel.unit)).toEqual(['km/h', 'km']);
    expect(panels[0].lines[0].paths).toHaveLength(2);
  });

  it('formats persisted export file sizes compactly', () => {
    expect(formatExportFileSize(0)).toBe('—');
    expect(formatExportFileSize(1536)).toBe('1.5 KB');
    expect(formatExportFileSize(5 * 1024 * 1024)).toBe('5.0 MB');
  });

  it('polls active export jobs conservatively and stops after terminal states', () => {
    expect(historyExportPollInterval([{ status: 'running' }])).toBe(HISTORY_EXPORT_POLL_MS.running);
    expect(historyExportPollInterval([{ status: 'queued' }])).toBe(HISTORY_EXPORT_POLL_MS.queued);
    expect(historyExportPollInterval([{ status: 'queued' }, { status: 'running' }])).toBe(HISTORY_EXPORT_POLL_MS.running);
    expect(historyExportPollInterval([{ status: 'completed' }, { status: 'failed' }])).toBe(false);
    expect(historyExportPollInterval()).toBe(false);
  });
});
