import { expect, tap } from '@git.zone/tstest/tapbundle';
import { BafClient, BafConfigFlow, BafIntegration, BafMapper, createBafDiscoveryDescriptor, type IBafSnapshot } from '../../ts/integrations/baf/index.js';

const rawData = {
  "fan_speed": 35,
  "direction": "forward",
  "temperature": 23
};

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

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

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

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

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

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

tap.test('exposes Big Ass Fans runtime services without fake live control', async () => {
  const runtime = await new BafIntegration().setup({ name: 'Big Ass Fans Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'baf', service: 'status', target: {} });
  const snapshot = status.data as IBafSnapshot;

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

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

  const executorRuntime = await new BafIntegration().setup({
    name: 'Big Ass Fans Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'baf', 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();
