import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DlinkMapper, type IDlinkSnapshot } from '../../ts/integrations/dlink/index.js';

const snapshot: IDlinkSnapshot = DlinkMapper.toSnapshot({
  id: 'aa:bb:cc:dd:ee:ff',
  host: '192.168.1.44',
  name: 'Kitchen Plug',
  modelName: 'DSP-W215',
  state: 'ON',
  temperature: '31',
  currentConsumption: '5.6',
  totalConsumption: '42.5',
  connected: true,
});

tap.test('maps D-Link snapshots to smart plug switch entities', async () => {
  const entities = DlinkMapper.toEntities(snapshot);
  const entity = entities[0];

  expect(entity.id).toEqual('switch.kitchen_plug');
  expect(entity.platform).toEqual('switch');
  expect(entity.state).toEqual('on');
  expect(entity.available).toBeTrue();
  expect(entity.attributes?.temperature).toEqual(31);
  expect(entity.attributes?.total_consumption).toEqual(42.5);
  expect(entity.attributes?.current_consumption).toEqual(5.6);
  expect(entity.attributes?.nativeType).toEqual('smart_plug_switch');
});

tap.test('maps D-Link snapshots to device features and state', async () => {
  const devices = DlinkMapper.toDevices(snapshot);
  const device = devices[0];

  expect(device.id).toEqual('dlink.device.aa_bb_cc_dd_ee_ff');
  expect(device.protocol).toEqual('http');
  expect(device.online).toBeTrue();
  expect(device.features.some((featureArg) => featureArg.id === 'power' && featureArg.writable)).toBeTrue();
  expect(device.features.some((featureArg) => featureArg.id === 'temperature')).toBeTrue();
  expect(device.state.find((stateArg) => stateArg.featureId === 'power')?.value).toBeTrue();
  expect(device.state.find((stateArg) => stateArg.featureId === 'current_consumption')?.value).toEqual(5.6);
});

tap.test('maps switch services to explicit D-Link HNAP commands', async () => {
  const command = DlinkMapper.commandForService(snapshot, {
    domain: 'switch',
    service: 'turn_off',
    target: { entityId: 'switch.kitchen_plug' },
    data: {},
  });

  expect(command?.type).toEqual('switch_turn_off');
  expect(command?.method).toEqual('hnap.SetSocketSettings');
  expect(command?.state).toEqual('OFF');
  expect(command?.host).toEqual('192.168.1.44');

  const setStateCommand = DlinkMapper.commandForService(snapshot, {
    domain: 'dlink',
    service: 'set_state',
    target: {},
    data: { state: 'ON' },
  });

  expect(setStateCommand?.type).toEqual('set_state');
  expect(setStateCommand?.state).toEqual('ON');
});

export default tap.start();
