import { describe, expect, it } from 'vitest';
import { accessRowsToCSV, formatSeconds, thresholdForProtocol, updateProtocolThreshold } from './access';

describe('access domain helpers', () => {
  it('formats duration without hiding sign or long offline windows', () => {
    expect(formatSeconds(45)).toBe('45 秒');
    expect(formatSeconds(3720)).toBe('1 小时 2 分');
    expect(formatSeconds(-3)).toBe('-3 秒');
    expect(formatSeconds(null)).toBe('—');
  });

  it('uses protocol override and updates without duplicates', () => {
    const config = { version: 1, defaultThresholdSec: 300, delayThresholdSec: 30, longOfflineSec: 1800, updatedBy: '', updatedAt: '', audit: [], protocols: [{ protocol: 'JT808', thresholdSec: 60 }] };
    expect(thresholdForProtocol(config, 'JT808')).toBe(60);
    expect(thresholdForProtocol(config, 'GB32960')).toBe(300);
    expect(updateProtocolThreshold(config.protocols, 'JT808', 120)).toEqual([{ protocol: 'JT808', thresholdSec: 120 }]);
  });

  it('exports explicit state and evidence fields', () => {
    const csv = accessRowsToCSV([{ vin: 'VIN1', plate: '粤A1', oem: '', model: '', company: '示范企业', protocol: 'JT808', provider: '', source: '', firstSeenAt: '', latestEventAt: '', latestReceivedAt: '', reportIntervalSec: null, dataDelaySec: 2, freshnessSec: 3, onlineState: 'online', thresholdSec: 60, latestMessageType: '位置,数据', latestEventId: '', latestError: '', delayAbnormal: false, firstSeenEvidence: '', firstSeenSource: '', reportIntervalEvidence: '', reportSampleCount: 2, expectedProtocols: ['GB32960', 'JT808', 'YUTONG_MQTT'], actualProtocols: ['JT808'], missingProtocols: ['GB32960', 'YUTONG_MQTT'], protocolStatuses: [{ protocol: 'JT808', expected: true, connected: true, provider: 'G7', firstSeenAt: '2026-07-01T00:00:00+08:00', latestEventAt: '', latestReceivedAt: '2026-07-15T09:00:00+08:00', reportIntervalSec: 10, dataDelaySec: 2, freshnessSec: 3, onlineState: 'online', thresholdSec: 60, delayAbnormal: false, firstSeenEvidence: '网关首次观测', reportIntervalEvidence: '连续样本' }], connectionState: 'incomplete', expectationEvidence: '平台标准接入基线' }]);
    expect(csv).toContain('在线');
    expect(csv).toContain('"GB32960/YUTONG_MQTT"');
    expect(csv).toContain('"2026-07-15T09:00:00+08:00"');
    expect(csv).toContain('"示范企业"');
  });
});
