import { describe, expect, it } from 'vitest';
import { MAX_MONITOR_SEARCH_TERMS, MONITOR_CACHE, MONITOR_REFRESH, monitorFilterScope, monitorMapQueryParams, monitorQueryParams, parseMonitorSearchTerms } from './useMonitorData';

describe('monitor query params', () => {
  it('keeps server-owned status filters and bounded list size', () => {
    const params = monitorQueryParams({ keyword: ' 沪A ', protocol: 'JT808', status: 'driving' }, 200);
    expect(params.get('keyword')).toBe('沪A');
    expect(params.get('protocol')).toBe('JT808');
    expect(params.get('status')).toBe('driving');
    expect(params.get('online')).toBeNull();
    expect(params.get('limit')).toBe('200');
  });

  it('retains compatibility online filter for online and offline states', () => {
    expect(monitorQueryParams({ keyword: '', protocol: '', status: 'offline' }, 200).get('online')).toBe('offline');
  });

  it('drops stale viewport bounds for a direct vehicle search', () => {
    const viewport = { zoom: 13, bounds: '103,29,105,31' };
    expect(monitorMapQueryParams({ keyword: '粤A1', protocol: '', status: '' }, viewport).has('bounds')).toBe(false);
    expect(monitorMapQueryParams({ keyword: '', protocol: '', status: '' }, viewport).get('bounds')).toBe(viewport.bounds);
  });

  it('normalizes pasted plates, removes duplicates, and sends one batch parameter', () => {
    expect(parseMonitorSearchTerms('粤ag18312\n川AHTWO1，粤AG18312  京A00001')).toEqual(['粤AG18312', '川AHTWO1', '京A00001']);
    const params = monitorQueryParams({ keyword: '粤AG18312\n川AHTWO1，粤AG18312', protocol: '', status: '' }, 200);
    expect(params.get('keywords')).toBe('粤AG18312,川AHTWO1');
    expect(params.get('keyword')).toBeNull();
    expect(parseMonitorSearchTerms(Array.from({ length: MAX_MONITOR_SEARCH_TERMS + 5 }, (_, index) => `粤A${index}`).join('\n'))).toHaveLength(MAX_MONITOR_SEARCH_TERMS);
  });

  it('builds filter scope independently from viewport and result limit', () => {
    const scope = new URLSearchParams(monitorFilterScope({ keyword: '粤a12345\n粤B67890', protocol: 'JT808', status: 'online' }));
    expect(scope.get('keywords')).toBe('粤A12345,粤B67890');
    expect(scope.get('protocol')).toBe('JT808');
    expect(scope.get('status')).toBe('online');
    expect(scope.get('online')).toBe('online');
    expect(scope.has('limit')).toBe(false);
  });
});

describe('monitor refresh cadence', () => {
  it('prioritizes one selected vehicle without polling the whole fleet too aggressively', () => {
    expect(MONITOR_REFRESH).toEqual({ summary: 30_000, fleet: 15_000, selected: 10_000, alerts: 15_000 });
    expect(MONITOR_REFRESH.selected).toBeLessThan(MONITOR_REFRESH.fleet);
    expect(MONITOR_REFRESH.fleet).toBeLessThan(MONITOR_REFRESH.summary);
  });

  it('does not retain inactive viewport payloads in the query cache', () => {
    expect(MONITOR_CACHE.mapGcTime).toBe(0);
  });
});
