import { expect, tap } from '@git.zone/tstest/tapbundle';
import { OpenthermGwMapper, type IOpenthermGwSnapshot } from '../../ts/integrations/opentherm_gw/index.js';

const snapshot: IOpenthermGwSnapshot = {
  gateway: {
    id: 'otgw-living-room',
    name: 'Living Room OTGW',
    host: '192.168.1.40',
    port: 25238,
    firmwareVersion: 'OpenTherm Gateway 5.1',
  },
  status: {
    gateway: {
      otgw_about: 'OpenTherm Gateway 5.1',
      otgw_mode: 'G',
      otgw_dhw_ovrd: 'A',
      otgw_gpio_a: 6,
      otgw_gpio_a_state: 0,
      central_heating_1_override: 1,
    },
    boiler: {
      slave_ch_active: 1,
      slave_dhw_active: 1,
      slave_flame_on: 1,
      slave_cooling_active: 0,
      slave_fault_indication: 0,
      control_setpoint: 55.5,
      ch_water_temp: 46.2,
      dhw_temp: 51.3,
      dhw_setpoint: 60,
      relative_mod_level: 34,
      ch_water_pressure: 1.7,
      master_ch_enabled: 1,
    },
    thermostat: {
      master_ch_enabled: 1,
      master_dhw_enabled: 1,
      room_temp: 20.4,
      room_setpoint: 21,
      outside_temp: 5.5,
    },
  },
  online: true,
  source: 'manual',
  updatedAt: '2026-01-01T00:00:00.000Z',
};

tap.test('maps OpenTherm Gateway devices', async () => {
  const devices = OpenthermGwMapper.toDevices(snapshot);
  expect(devices.map((deviceArg) => deviceArg.id)).toContain('opentherm_gw.gateway.otgw_living_room');
  expect(devices.map((deviceArg) => deviceArg.id)).toContain('opentherm_gw.boiler.otgw_living_room');
  expect(devices.map((deviceArg) => deviceArg.id)).toContain('opentherm_gw.thermostat.otgw_living_room');
});

tap.test('maps climate sensors binary sensors and switches', async () => {
  const entities = OpenthermGwMapper.toEntities(snapshot);
  const climate = entities.find((entityArg) => entityArg.id === 'climate.living_room_otgw_thermostat');
  const waterTemp = entities.find((entityArg) => entityArg.id === 'sensor.living_room_otgw_boiler_central_heating_1_water_temperature');
  const flame = entities.find((entityArg) => entityArg.id === 'binary_sensor.living_room_otgw_boiler_flame');
  const switchEntity = entities.find((entityArg) => entityArg.id === 'switch.living_room_otgw_central_heating_1_override');

  expect(climate?.platform).toEqual('climate');
  expect(climate?.state).toEqual('heat');
  expect(climate?.attributes?.hvacAction).toEqual('heating');
  expect(climate?.attributes?.currentTemperature).toEqual(20.4);
  expect(waterTemp?.state).toEqual(46.2);
  expect(waterTemp?.attributes?.unitOfMeasurement).toEqual('C');
  expect(flame?.platform).toEqual('binary_sensor');
  expect(flame?.state).toEqual('on');
  expect(switchEntity?.platform).toEqual('switch');
  expect(switchEntity?.state).toEqual('on');
});

export default tap.start();
