import { expect, tap } from '@git.zone/tstest/tapbundle';
import { BoschShcConfigFlow, createBoschShcDiscoveryDescriptor } from '../../ts/integrations/bosch_shc/index.js';
import type { IBoschShcSnapshot } from '../../ts/integrations/bosch_shc/index.js';

tap.test('matches Bosch SHC zeroconf records and validates manual candidates', async () => {
  const descriptor = createBoschShcDiscoveryDescriptor();
  const mdnsMatcher = descriptor.getMatchers()[0];
  const mdnsResult = await mdnsMatcher.matches({
    name: 'Bosch SHC [AA:BB:CC:DD:EE:FF]._http._tcp.local.',
    type: '_http._tcp.local.',
    host: 'bosch-shc.local',
    port: 80,
  }, {});

  expect(mdnsResult.matched).toBeTrue();
  expect(mdnsResult.normalizedDeviceId).toEqual('aa-bb-cc-dd-ee-ff');
  expect(mdnsResult.candidate?.integrationDomain).toEqual('bosch_shc');
  expect(mdnsResult.candidate?.manufacturer).toEqual('Bosch');

  const manualMatcher = descriptor.getMatchers()[1];
  const manualResult = await manualMatcher.matches({ host: '192.168.1.10' }, {});
  expect(manualResult.matched).toBeTrue();
  expect(manualResult.candidate?.host).toEqual('192.168.1.10');

  const validator = descriptor.getValidators()[0];
  const validResult = await validator.validate({
    source: 'manual',
    integrationDomain: 'bosch_shc',
    host: '192.168.1.10',
    id: 'AA:BB:CC:DD:EE:FF',
  }, {});
  expect(validResult.matched).toBeTrue();
});

tap.test('config flow preserves credentials and refuses native pairing without executor', async () => {
  const flow = new BoschShcConfigFlow();
  const step = await flow.start({ source: 'manual', integrationDomain: 'bosch_shc', host: '192.168.1.10' }, {});

  const pairing = await step.submit?.({ host: '192.168.1.10', password: 'secret' });
  expect(pairing?.kind).toEqual('error');
  expect(pairing?.error).toContain('executor');

  const done = await step.submit?.({ host: '192.168.1.10', sslCertificate: '/config/bosch/cert.pem', sslKey: '/config/bosch/key.pem', token: 'token:bosch-shc' });
  expect(done?.kind).toEqual('done');
  expect(done?.config?.host).toEqual('192.168.1.10');
  expect(done?.config?.sslCertificate).toEqual('/config/bosch/cert.pem');

  const snapshot: IBoschShcSnapshot = { host: '192.168.1.10', devices: [], information: { macAddress: 'AA:BB:CC:DD:EE:FF' } };
  const snapshotDone = await step.submit?.({ host: '192.168.1.10', snapshotJson: JSON.stringify(snapshot) });
  expect(snapshotDone?.kind).toEqual('done');
  expect(snapshotDone?.config?.snapshot?.information?.macAddress).toEqual('AA:BB:CC:DD:EE:FF');
});

export default tap.start();
