import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Eq3btsmartClient, Eq3btsmartConfigFlow, Eq3btsmartIntegration, Eq3btsmartMapper, HomeAssistantEq3btsmartIntegration, createEq3btsmartDiscoveryDescriptor, eq3btsmartProfile, type IEq3btsmartSnapshot } from '../../ts/integrations/eq3btsmart/index.js';

const rawData = {
  device: {
    id: 'eq3-aa-bb-cc-dd-ee-ff',
    name: 'Hall Radiator Valve',
    manufacturer: 'eQ-3 AG',
    model: 'CC-RT-BLE-EQ',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
    attributes: {
      connection: 'bluetooth',
    },
  },
  entities: [
    { id: 'thermostat', name: 'Thermostat', platform: 'climate', state: { currentTemperature: 20.5, targetTemperature: 21, hvacMode: 'heat', presetMode: 'none' }, writable: true, unit: 'C' },
    { id: 'low_battery', name: 'Low Battery', platform: 'binary_sensor', state: false, deviceClass: 'battery' },
    { id: 'window', name: 'Window', platform: 'binary_sensor', state: false, deviceClass: 'window' },
    { id: 'valve', name: 'Valve', platform: 'sensor', state: 34, unit: '%', stateClass: 'measurement' },
    { id: 'comfort', name: 'Comfort Temperature', platform: 'number', state: 21, unit: 'C', writable: true },
    { id: 'boost', name: 'Boost', platform: 'switch', state: false, writable: true },
  ],
};

tap.test('matches manual eQ-3 candidates and creates config flow output', async () => {
  const descriptor = createEq3btsmartDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'eq3btsmart-manual-match');
  const result = await matcher!.matches({ id: 'AA:BB:CC:DD:EE:FF', name: 'CC-RT-BLE Hall', metadata: { rawData } }, {});

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

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

  const done = await (await new Eq3btsmartConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('AA:BB:CC:DD:EE:FF');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps eQ-3 raw snapshots to runtime devices and entities', async () => {
  const client = new Eq3btsmartClient({ name: 'Hall Radiator Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const devices = Eq3btsmartMapper.toDevices(snapshot);
  const entities = Eq3btsmartMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('eq3btsmart');
  expect(devices[0].manufacturer).toEqual('eQ-3 AG');
  expect(entities.some((entityArg) => entityArg.platform === 'climate')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'number')).toBeTrue();
});

tap.test('exposes eQ-3 runtime services, HA alias, and unsupported control without executor', async () => {
  const alias = new HomeAssistantEq3btsmartIntegration();
  expect(alias instanceof Eq3btsmartIntegration).toBeTrue();
  expect(alias.domain).toEqual('eq3btsmart');
  expect(eq3btsmartProfile.metadata.iotClass).toEqual('local_polling');
  expect(eq3btsmartProfile.metadata.requirements).toEqual(['eq3btsmart==2.3.0']);
  expect(eq3btsmartProfile.metadata.configFlow).toBeTrue();

  const runtime = await new Eq3btsmartIntegration().setup({ name: 'Hall Radiator Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'eq3btsmart', service: 'status', target: {} });
  const snapshot = status.data as IEq3btsmartSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.callService!({ domain: 'eq3btsmart', service: 'refresh', target: {} })).success).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Hall Radiator Valve');

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

export default tap.start();
