import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FlexitBacnetClient, FlexitBacnetConfigFlow, FlexitBacnetIntegration, FlexitBacnetMapper, HomeAssistantFlexitBacnetIntegration, createFlexitBacnetDiscoveryDescriptor, flexitBacnetProfile, type IFlexitBacnetSnapshot, type TFlexitBacnetRawData } from '../../ts/integrations/flexit_bacnet/index.js';

const rawData: TFlexitBacnetRawData = {
  host: '192.0.2.10',
  device_id: 2,
  device_name: 'Flexit Nordic Test',
  serial_number: 'FXBACNET123',
  model: 'Nordic S4',
  operation_mode: 'home',
  ventilation_mode: 'home',
  room_temperature: 21.4,
  air_temp_setpoint_home: 20,
  outside_air_temperature: 5.5,
  supply_air_fan_rpm: 1180,
  air_filter_polluted: false,
  electric_heater: true,
  fan_setpoint_supply_air_home: 55,
};

tap.test('matches manual Flexit BACnet candidates and creates config flow output', async () => {
  const descriptor = createFlexitBacnetDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'flexit_bacnet-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'FXBACNET123', host: '192.0.2.10', name: 'Flexit Nordic Test', metadata: { rawData, deviceId: 2 } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('flexit_bacnet');

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new FlexitBacnetConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.0.2.10');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Flexit BACnet raw snapshots to runtime devices and entities', async () => {
  const client = new FlexitBacnetClient({ rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = FlexitBacnetMapper.toSnapshotFromRaw({}, rawData);
  const devices = FlexitBacnetMapper.toDevices(mappedSnapshot);
  const entities = FlexitBacnetMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('flexit_bacnet');
  expect(devices[0].manufacturer).toEqual('Flexit');
  expect(entities.some((entityArg) => entityArg.id === 'climate.flexit_nordic_test_climate')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.flexit_nordic_test_air_filter_polluted')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'number.flexit_nordic_test_home_supply_fan_setpoint')).toBeTrue();
});

tap.test('exposes Flexit BACnet read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FlexitBacnetIntegration();
  const alias = new HomeAssistantFlexitBacnetIntegration();
  expect(alias instanceof FlexitBacnetIntegration).toBeTrue();
  expect(alias.domain).toEqual('flexit_bacnet');
  expect(integration.status).toEqual('read-only-runtime');
  expect(flexitBacnetProfile.metadata.configFlow).toEqual(true);
  expect(flexitBacnetProfile.metadata.qualityScale).toEqual('silver');
  expect(flexitBacnetProfile.metadata.requirements).toEqual(['flexit_bacnet==2.2.3']);
  expect(flexitBacnetProfile.metadata.codeowners).toEqual(['@lellky', '@piotrbulinski']);

  const runtime = await integration.setup({ rawData }, {});
  const status = await runtime.callService!({ domain: 'flexit_bacnet', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'flexit_bacnet', service: 'refresh', target: {} });
  const snapshot = status.data as IFlexitBacnetSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.entities.some((entityArg) => entityArg.id === 'climate')).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Flexit Nordic Test');

  const command = await runtime.callService!({ domain: 'climate', service: 'set_temperature', target: { entityId: 'climate.flexit_nordic_test_climate' }, data: { temperature: 20 } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
