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

const config = {
  host: 'mqtt.local',
  discoveryMessages: [{
    topic: 'homeassistant/device/kitchen_sensor/config',
    payload: JSON.stringify({
      dev: { ids: 'kitchen-sensor-1', name: 'Kitchen Sensor', mf: 'Example', mdl: 'MQTT Multi Sensor', sw: '1.0' },
      o: { name: 'example2mqtt', sw: '2.0' },
      '~': 'kitchen/sensor',
      stat_t: '~/state',
      cmps: {
        temperature: { p: 'sensor', name: 'Temperature', uniq_id: 'kitchen_temperature', dev_cla: 'temperature', unit_of_meas: 'C', val_tpl: '{{ value_json.temperature }}' },
        relay: { p: 'switch', name: 'Relay', uniq_id: 'kitchen_relay', cmd_t: 'kitchen/relay/set', stat_t: 'kitchen/relay/state' },
      },
    }),
  }],
  retainedMessages: [
    { topic: 'kitchen/sensor/state', payload: '{"temperature":21.5}' },
    { topic: 'kitchen/relay/state', payload: 'ON' },
  ],
};

tap.test('maps MQTT discovery payloads to devices and entities', async () => {
  const snapshot = MqttMapper.toSnapshot(config);
  const devices = MqttMapper.toDevices(snapshot);
  const entities = MqttMapper.toEntities(snapshot);
  expect(devices.some((deviceArg) => deviceArg.id === 'mqtt.device.kitchen_sensor_1')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.uniqueId === 'kitchen_temperature' && entityArg.state === 21.5)).toBeTrue();
  expect(entities.some((entityArg) => entityArg.uniqueId === 'kitchen_relay' && entityArg.state === 'on')).toBeTrue();
});

export default tap.start();
