import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DovadoClient, DovadoConfigFlow, DovadoIntegration, DovadoMapper, HomeAssistantDovadoIntegration, createDovadoDiscoveryDescriptor, dovadoProfile, type IDovadoSnapshot } from '../../ts/integrations/dovado/index.js';

const rawData = {
  'product name': 'Dovado Pro',
  'modem status': 'CONNECTED',
  'signal strength': '76% (LTE)',
  'sms unread': '2',
  'traffic modem tx': 2300000,
  'traffic modem rx': 5700000,
  connected: true,
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('dovado');
  expect(devices[0].manufacturer).toEqual('Dovado');
  expect(entities.length > 0).toBeTrue();
});

tap.test('exposes Dovado runtime services without fake live SMS control', async () => {
  expect(new HomeAssistantDovadoIntegration().domain).toEqual('dovado');
  expect(dovadoProfile.status).toEqual('control-runtime');
  expect(dovadoProfile.metadata.qualityScale).toEqual('legacy');
  expect(dovadoProfile.metadata.requirements).toEqual(['dovado==0.4.1']);
  expect(dovadoProfile.metadata.configFlow).toBeFalse();

  const runtime = await new DovadoIntegration().setup({ name: 'Dovado Router Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'dovado', service: 'status', target: {} });
  const snapshot = status.data as IDovadoSnapshot;

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

  const liveCommand = await runtime.callService!({ domain: 'notify', service: 'send_message', target: {}, data: { message: 'hello', target: ['+15550101'] } });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();
});

export default tap.start();
