import { expect, tap } from '@git.zone/tstest/tapbundle';
import { BluetoothLeTrackerMapper } from '../../ts/integrations/bluetooth_le_tracker/index.js';

const lastSeen = Date.now();
const repeatedAdvertisements = Array.from({ length: 5 }, (_, indexArg) => ({
  address: 'AA:BB:CC:DD:EE:FF',
  name: indexArg === 4 ? 'Backpack Tag' : undefined,
  rssi: -60 - indexArg,
  battery: 87,
  connectable: false,
  time: lastSeen + indexArg,
}));

tap.test('maps tracked BLE advertisements into devices and device-tracker-like entities', async () => {
  const snapshot = BluetoothLeTrackerMapper.toSnapshot({
    trackNewDevices: true,
    trackBattery: true,
    advertisements: repeatedAdvertisements,
    knownDevices: [{ mac: 'BLE_11:22:33:44:55:66', name: 'Ignored Beacon', track: false }],
  });
  const devices = BluetoothLeTrackerMapper.toDevices(snapshot);
  const entities = BluetoothLeTrackerMapper.toEntities(snapshot);

  expect(snapshot.devices.length).toEqual(1);
  expect(snapshot.devices[0].address).toEqual('aa:bb:cc:dd:ee:ff');
  expect(snapshot.devices[0].advertisementCount).toEqual(5);
  expect(devices[0].id).toEqual('bluetooth_le_tracker.device.aa_bb_cc_dd_ee_ff');
  expect(devices[0].metadata?.haMac).toEqual('BLE_AA:BB:CC:DD:EE:FF');
  expect(entities.find((entityArg) => entityArg.uniqueId === 'bluetooth_le_tracker_presence_aa_bb_cc_dd_ee_ff')?.state).toEqual('on');
  expect(entities.find((entityArg) => entityArg.uniqueId === 'bluetooth_le_tracker_state_aa_bb_cc_dd_ee_ff')?.state).toEqual('home');
  expect(entities.find((entityArg) => entityArg.uniqueId === 'bluetooth_le_tracker_battery_aa_bb_cc_dd_ee_ff')?.state).toEqual(87);
});

tap.test('keeps new BLE devices untracked until the HA sighting threshold is reached', async () => {
  const snapshot = BluetoothLeTrackerMapper.toSnapshot({
    trackNewDevices: true,
    advertisements: repeatedAdvertisements.slice(0, 4),
  });

  expect(snapshot.devices.length).toEqual(0);
});

export default tap.start();
