import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DsmrReaderClient, DsmrReaderConfigFlow, DsmrReaderIntegration, DsmrReaderMapper, HomeAssistantDsmrReaderIntegration, createDsmrReaderDiscoveryDescriptor, dsmrReaderProfile, type IDsmrReaderSnapshot } from '../../ts/integrations/dsmr_reader/index.js';

const rawData = {
  electricity_currently_delivered: 1.24,
  electricity_tariff: 'low',
  gas_usage: 12.8,
};

tap.test('matches manual DSMR Reader candidates and creates config flow output', async () => {
  const descriptor = createDsmrReaderDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'dsmr_reader-manual-match');
  const result = await matcher!.matches({ host: 'mqtt.local', name: 'DSMR Reader', metadata: { rawData } }, {});

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

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

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

tap.test('maps DSMR Reader raw snapshots to runtime devices and entities', async () => {
  const client = new DsmrReaderClient({ name: 'DSMR Reader Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = DsmrReaderMapper.toDevices(snapshot);
  const entities = DsmrReaderMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('dsmr_reader');
  expect(devices[0].protocol).toEqual('mqtt');
  expect(entities.length).toEqual(3);
});

tap.test('exposes DSMR Reader read-only runtime without fake live control', async () => {
  const integration = new HomeAssistantDsmrReaderIntegration();
  expect(integration.domain).toEqual('dsmr_reader');
  expect(dsmrReaderProfile.status).toEqual('read-only-runtime');
  expect(dsmrReaderProfile.metadata.dependencies).toEqual(['mqtt']);
  expect(dsmrReaderProfile.metadata.configFlow).toEqual(true);

  const runtime = await new DsmrReaderIntegration().setup({ name: 'DSMR Reader Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'dsmr_reader', service: 'status', target: {} });
  const snapshot = status.data as IDsmrReaderSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('DSMR Reader Runtime');

  const controlCommand = await runtime.callService!({ domain: 'dsmr_reader', service: 'turn_on', target: {} });
  expect(controlCommand.success).toBeFalse();
  expect(Boolean(controlCommand.error)).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
