import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ApcupsdClient, ApcupsdMapper, type IApcupsdSnapshot } from '../../ts/integrations/apcupsd/index.js';

const rawStatus = `APC      : 001,043,1036
DATE     : 2026-01-01 00:00:00 +0000
HOSTNAME : nas
VERSION  : 3.14.14
UPSNAME  : Office UPS
MODEL    : Back-UPS ES 700
STATUS   : ONLINE
LINEV    : 230.0 Volts
LOADPCT  : 21.0 Percent
BCHARGE  : 98.0 Percent
TIMELEFT : 42.5 Minutes
BATTV    : 13.6 Volts
LINEFREQ : 50.0 Hz
OUTPUTV  : 230.1 Volts
NOMPOWER : 405 Watts
SERIALNO : AS1234567890
STATFLAG : 0x05000008 Status Flag
END APC  : 2026-01-01 00:00:00 +0000
`;

tap.test('parses APCUPSd status output into a safe snapshot', async () => {
  const snapshot = await new ApcupsdClient({ rawStatus }).getSnapshot();
  expect(snapshot.ups.name).toEqual('Office UPS');
  expect(snapshot.ups.serialNumber).toEqual('AS1234567890');
  expect(snapshot.ups.lineOnline).toBeTrue();
  expect(snapshot.battery.chargePercent).toEqual(98);
  expect(snapshot.battery.timeLeftMinutes).toEqual(42.5);
  expect(snapshot.power.lineVoltage).toEqual(230);
  expect(snapshot.power.loadPercent).toEqual(21);
});

tap.test('maps APCUPSd snapshot to canonical devices and entities', async () => {
  const snapshot = await new ApcupsdClient({ rawStatus }).getSnapshot();
  const devices = ApcupsdMapper.toDevices(snapshot);
  const entities = ApcupsdMapper.toEntities(snapshot);

  expect(devices.some((deviceArg) => deviceArg.id === 'apcupsd.ups.as1234567890')).toBeTrue();
  expect(entities.find((entityArg) => entityArg.id === 'binary_sensor.office_ups_online_status')?.state).toEqual('on');
  expect(entities.find((entityArg) => entityArg.id === 'sensor.office_ups_battery_charge')?.state).toEqual(98);
  expect(entities.find((entityArg) => entityArg.id === 'sensor.office_ups_input_voltage')?.attributes?.unit).toEqual('V');
  expect(entities.find((entityArg) => entityArg.id === 'sensor.office_ups_nominal_output_power')?.state).toEqual(405);
});

tap.test('maps offline snapshots without inventing unavailable sensor values', async () => {
  const snapshot: IApcupsdSnapshot = {
    ups: { id: 'offline-ups', name: 'Offline UPS' },
    battery: {},
    power: {},
    status: {},
    online: false,
    updatedAt: '2026-01-01T00:00:00.000Z',
  };
  const entities = ApcupsdMapper.toEntities(snapshot);
  expect(entities.find((entityArg) => entityArg.id === 'sensor.offline_ups_status')?.available).toBeFalse();
  expect(entities.some((entityArg) => entityArg.id === 'sensor.offline_ups_battery_charge')).toBeFalse();
});

export default tap.start();
