import { expect, tap } from '@git.zone/tstest/tapbundle';
import { VenstarClient, VenstarConfigFlow, VenstarIntegration, VenstarMapper, createVenstarDiscoveryDescriptor, type IVenstarSnapshot } from '../../ts/integrations/venstar/index.js';

const rawData = {
  "temperature": 22.1,
  "humidity": 41,
  "mode": "heat"
};

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

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

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

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

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

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

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

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

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

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

export default tap.start();
