import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HeatmiserClient, HeatmiserConfigFlow, HeatmiserIntegration, HeatmiserMapper, HomeAssistantHeatmiserIntegration, createHeatmiserDiscoveryDescriptor, heatmiserProfile, type IHeatmiserSnapshot, type THeatmiserRawData } from '../../ts/integrations/heatmiser/index.js';

const rawData: THeatmiserRawData = {
  thermostats: [
    {
      id: 1,
      name: 'Hallway',
      floorTemp: 21,
      targetTemp: 22,
      currentState: 1,
      temperatureFormat: 'C',
    },
    {
      id: 2,
      name: 'Bedroom',
      floorTemp: 18,
      targetTemp: 16,
      currentState: 0,
      temperatureFormat: 'C',
    },
  ],
};

tap.test('matches manual Heatmiser candidates and creates config flow output', async () => {
  const descriptor = createHeatmiserDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'heatmiser-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: 'heatmiser.local', port: 4242, name: 'Heatmiser UH1', metadata: { rawData } }, {});

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

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

  const done = await (await new HeatmiserConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('heatmiser.local');
  expect(done.config?.port).toEqual(4242);
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Heatmiser raw snapshots to runtime devices and entities', async () => {
  const client = new HeatmiserClient({ host: 'heatmiser.local', port: 4242, rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = HeatmiserMapper.toSnapshotFromRaw({ host: 'heatmiser.local', port: 4242 }, rawData);
  const devices = HeatmiserMapper.toDevices(mappedSnapshot);
  const entities = HeatmiserMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('heatmiser');
  expect(devices[0].manufacturer).toEqual('Heatmiser');
  expect(entities.some((entityArg) => entityArg.id === 'climate.heatmiser_thermostat_1')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'climate.heatmiser_thermostat_2')).toBeTrue();
  expect(entities.find((entityArg) => entityArg.id === 'climate.heatmiser_thermostat_2')?.state).toEqual('off');
});

tap.test('exposes Heatmiser read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HeatmiserIntegration();
  const alias = new HomeAssistantHeatmiserIntegration();
  expect(alias instanceof HeatmiserIntegration).toBeTrue();
  expect(alias.domain).toEqual('heatmiser');
  expect(integration.status).toEqual('read-only-runtime');
  expect(heatmiserProfile.metadata.configFlow).toEqual(false);
  expect(heatmiserProfile.metadata.qualityScale).toEqual('legacy');
  expect(heatmiserProfile.metadata.requirements).toEqual(['heatmiserV3==2.0.4']);

  const runtime = await integration.setup({ host: 'heatmiser.local', port: 4242, rawData }, {});
  const status = await runtime.callService!({ domain: 'heatmiser', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'heatmiser', service: 'refresh', target: {} });
  const snapshot = status.data as IHeatmiserSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.entities()).length).toEqual(2);

  const command = await runtime.callService!({ domain: 'climate', service: 'set_temperature', target: { entityId: 'climate.heatmiser_thermostat_1' }, 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();
