import { afterEach, describe, expect, test, vi } from 'vitest';
import { httpErrorMessage, loadPrototypeRealtimeVehicles } from './realData';

afterEach(() => {
  delete window.__LINGNIU_APP_CONFIG__;
  window.sessionStorage.clear();
  vi.restoreAllMocks();
});

describe('httpErrorMessage', () => {
  test('preserves HTTP status and compact response body', async () => {
    const response = new Response(' database   connection failed ', { status: 500 });

    await expect(httpErrorMessage(response)).resolves.toBe('HTTP 500: database connection failed');
  });

  test('marks an empty HTTP error body explicitly', async () => {
    const response = new Response('', { status: 500 });

    await expect(httpErrorMessage(response)).resolves.toBe('HTTP 500: empty response body');
  });
});

describe('loadPrototypeRealtimeVehicles', () => {
  test('merges realtime snapshot parsed_json fields into the same vehicle as realtime locations', async () => {
    window.__LINGNIU_APP_CONFIG__ = { prototypeUseRealData: true };
    const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
      const url = String(input);
      if (url.includes('/api/realtime/locations')) {
        return Promise.resolve(new Response(JSON.stringify({
          items: [{
            protocol: 'GB32960',
            vin: 'LB9A32A22R0LS1456',
            plate: '粤AGP6637',
            event_time: '2026-07-09 10:38:21.000',
            latitude: 23.093449,
            longitude: 113.159489,
            speed_kmh: 26,
            total_mileage_km: 22734.4,
            soc_percent: 68,
            received_at: '2026-07-09 10:38:24.185',
            updated_at: '2026-07-09 10:38:25.000'
          }],
          total: 1
        })));
      }
      if (url.includes('/api/realtime/snapshots')) {
        return Promise.resolve(new Response(JSON.stringify({
          items: [{
            protocol: 'GB32960',
            vin: 'LB9A32A22R0LS1456',
            plate: '粤AGP6637',
            platform_name: 'Hyundai',
            peer: '8.134.95.166:35062',
            parsed_json: JSON.stringify({
              'gb32960.vehicle.speed_kmh': '32',
              'gb32960.vehicle.total_mileage_km': '22734.5',
              'gb32960.gd_fc_stack.stack_water_outlet_temp_c': '65',
              'gb32960.gd_fc_auxiliary.subsystems.subsystem_1.water_pump_voltage_v': '340'
            }),
            event_time: '2026-07-09 10:38:31.000',
            received_at: '2026-07-09 10:38:34.000',
            updated_at: '2026-07-09 10:38:35.000'
          }],
          total: 1
        })));
      }
      return Promise.reject(new Error(`unexpected fetch ${url}`));
    });

    const state = await loadPrototypeRealtimeVehicles(10);

    expect(fetchMock).toHaveBeenCalledWith('/api/realtime/locations?limit=10&offset=0', expect.any(Object));
    expect(fetchMock).toHaveBeenCalledWith('/api/realtime/snapshots?limit=10&offset=0', expect.any(Object));
    expect(state.status).toBe('ready');
    expect(state.vehicles).toHaveLength(1);
    const vehicle = state.vehicles[0];
    expect(vehicle.flatFields.GB32960['gb32960.gd_fc_stack.stack_water_outlet_temp_c']).toBe('65');
    expect(vehicle.flatFields.GB32960['gb32960.gd_fc_auxiliary.subsystems.subsystem_1.water_pump_voltage_v']).toBe('340');
    expect(vehicle.sources[0].endpoint).toBe('8.134.95.166:35062');
    expect(vehicle.sources[0].fieldCount).toBeGreaterThan(10);
  });

  test('converts Yutong MQTT total_mileage meters to source totalMileageKm while preserving raw flat field', async () => {
    window.__LINGNIU_APP_CONFIG__ = { prototypeUseRealData: true };
    vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
      const url = String(input);
      if (url.includes('/api/realtime/locations')) {
        return Promise.resolve(new Response(JSON.stringify({ items: [], total: 0 })));
      }
      if (url.includes('/api/realtime/snapshots')) {
        return Promise.resolve(new Response(JSON.stringify({
          items: [{
            protocol: 'YUTONG_MQTT',
            vin: 'LMRKH9AC2R1004087',
            plate: '沪A65516F',
            peer: 'mqtt://yutong/ytforward/shln/3',
            parsed_json: JSON.stringify({
              'yutong_mqtt.data.longitude': '121.075044',
              'yutong_mqtt.data.latitude': '30.590921',
              'yutong_mqtt.data.meter_speed': '27',
              'yutong_mqtt.data.total_mileage': '119925000',
              'yutong_mqtt.data.battery_capacity_soc': '78.4'
            }),
            event_time: '2026-07-09 10:50:37.945',
            received_at: '2026-07-09 10:50:37.967'
          }],
          total: 1
        })));
      }
      return Promise.reject(new Error(`unexpected fetch ${url}`));
    });

    const state = await loadPrototypeRealtimeVehicles(10);

    expect(state.status).toBe('ready');
    expect(state.vehicles).toHaveLength(1);
    const vehicle = state.vehicles[0];
    expect(vehicle.longitude).toBe(121.075044);
    expect(vehicle.latitude).toBe(30.590921);
    expect(vehicle.soc).toBe(78.4);
    expect(vehicle.sources[0].speedKph).toBe(27);
    expect(vehicle.sources[0].totalMileageKm).toBe(119925);
    expect(vehicle.flatFields.YUTONG_MQTT['yutong_mqtt.data.total_mileage']).toBe('119925000');
  });
});
