import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GoodweConfigFlow, GoodweMapper, createGoodweDiscoveryDescriptor, goodweDefaultUdpPort, type IGoodweRawData } from '../../ts/integrations/goodwe/index.js';

tap.test('matches manual GoodWe host entries and creates config flow output', async () => {
  const descriptor = createGoodweDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'goodwe-manual-match');
  const match = await matcher!.matches({ host: '192.168.1.50', name: 'Garage GoodWe', modelFamily: 'ET', serialNumber: 'ETU123456789' }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.integrationDomain).toEqual('goodwe');
  expect(match.candidate?.host).toEqual('192.168.1.50');
  expect(match.candidate?.port).toEqual(goodweDefaultUdpPort);
  expect(match.normalizedDeviceId).toEqual('ETU123456789');

  const done = await (await new GoodweConfigFlow().start(match.candidate!, {})).submit!({ port: 502, modelFamily: 'ET' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.168.1.50');
  expect(done.config?.port).toEqual(502);
  expect(done.config?.modelFamily).toEqual('ET');
  expect(done.config?.serialNumber).toEqual('ETU123456789');
});

tap.test('matches manual snapshots without requiring a live UDP inverter', async () => {
  const rawData: Partial<IGoodweRawData> = {
    deviceInfo: { name: 'Snapshot GoodWe', serialNumber: 'SNAP123', model: 'GW10K-ET', modelFamily: 'ET' },
    runtimeData: { ppv: 3200, active_power: 2400, battery_soc: 71 },
    operationMode: 'general',
  };
  const snapshot = GoodweMapper.toSnapshot({ config: { name: 'Snapshot GoodWe' }, rawData, online: true, source: 'manual' });
  const matcher = createGoodweDiscoveryDescriptor().getMatchers()[0];
  const match = await matcher.matches({ metadata: { snapshot } }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.host).toBeUndefined();
  expect(match.candidate?.metadata?.snapshot).toEqual(snapshot);

  const done = await (await new GoodweConfigFlow().start(match.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.snapshot?.inverter.serialNumber).toEqual('SNAP123');
  expect(done.config?.host).toBeUndefined();
});

tap.test('rejects GoodWe-looking candidates without a usable local source', async () => {
  const validation = await createGoodweDiscoveryDescriptor().getValidators()[0].validate({
    source: 'manual',
    integrationDomain: 'goodwe',
    name: 'GoodWe without host',
  }, {});

  expect(validation.matched).toBeFalse();
  expect(validation.reason).toEqual('GoodWe candidate lacks a host, injected client, snapshot, or raw data.');
});

export default tap.start();
