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

const wirelessResponse = "{active_wireless::'AA:BB:CC:DD:EE:FF','ath0','11:22:33:44:55:66'}";
const lanResponse = "{arp_table::'192.168.1.10','AA:BB:CC:DD:EE:FF','br0','192.168.1.11','11:22:33:44:55:66','br0'}{dhcp_leases::'phone','192.168.1.10','AA:BB:CC:DD:EE:FF','hostid','3600','laptop','192.168.1.11','11:22:33:44:55:66','hostid2','7200'}";

tap.test('maps DD-WRT live status data to snapshot and entities', async () => {
  const snapshot = DdwrtMapper.toSnapshot({
    host: '192.168.1.1',
    name: 'Lab Router',
    rawStatus: {
      wireless: DdwrtMapper.parseDdwrtResponse(wirelessResponse),
      lan: DdwrtMapper.parseDdwrtResponse(lanResponse),
    },
  });
  const entities = DdwrtMapper.toEntities(snapshot);

  expect(snapshot.connected).toBeTrue();
  expect(snapshot.router.wirelessOnly).toBeTrue();
  expect(snapshot.clients.length).toEqual(2);
  expect(snapshot.clients[0].macAddress).toEqual('aa:bb:cc:dd:ee:ff');
  expect(snapshot.clients[0].hostname).toEqual('phone');
  expect(snapshot.sensors.active_wireless_clients).toEqual(2);
  expect(snapshot.sensors.active_lan_clients).toEqual(2);
  expect(snapshot.sensors.dhcp_leases).toEqual(2);
  expect(entities.find((entityArg) => entityArg.id === 'binary_sensor.phone_connected')?.attributes?.nativePlatform).toEqual('device_tracker');
  expect(entities.find((entityArg) => entityArg.id === 'sensor.lab_router_tracked_clients')?.state).toEqual(2);
});

tap.test('maps LAN tracking mode to device definitions and delegated commands', async () => {
  const snapshot = DdwrtMapper.toSnapshot({
    host: '192.168.1.1',
    name: 'Lab Router',
    wirelessOnly: false,
    rawStatus: {
      wireless: DdwrtMapper.parseDdwrtResponse(wirelessResponse),
      lan: DdwrtMapper.parseDdwrtResponse(lanResponse),
    },
  });
  const devices = DdwrtMapper.toDevices(snapshot);
  const command = DdwrtMapper.commandForService(snapshot, { domain: 'ddwrt', service: 'reboot', target: {}, data: {} });

  expect(snapshot.router.wirelessOnly).toBeFalse();
  expect(snapshot.clients.map((clientArg) => clientArg.hostname)).toEqual(['phone', 'laptop']);
  expect(devices[0].id).toEqual('ddwrt.router.192_168_1_1');
  expect(devices.some((deviceArg) => deviceArg.id === 'ddwrt.client.aa_bb_cc_dd_ee_ff')).toBeTrue();
  expect(devices[0].features.some((featureArg) => featureArg.id === 'tracked_clients')).toBeTrue();
  expect(command?.action).toEqual('reboot');
  expect(command?.method).toEqual('executor');
});

export default tap.start();
