import { expect, tap } from '@git.zone/tstest/tapbundle';
import { VictronGxClient, VictronGxConfigFlow, VictronGxIntegration, VictronGxMapper, createVictronGxDiscoveryDescriptor, type IVictronGxSnapshot } from '../../ts/integrations/victron_gx/index.js';

const rawData = {
  "battery_soc": 82,
  "pv_power": 1200,
  "grid_connected": true
};

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

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

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

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

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

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

tap.test('exposes Victron GX runtime services without fake live control', async () => {
  const runtime = await new VictronGxIntegration().setup({ name: 'Victron GX Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'victron_gx', service: 'status', target: {} });
  const snapshot = status.data as IVictronGxSnapshot;

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

  const liveCommand = await runtime.callService!({ domain: 'victron_gx', service: 'turn_on', target: {} });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();

  const executorRuntime = await new VictronGxIntegration().setup({
    name: 'Victron GX Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'victron_gx', service: 'turn_on', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
