import { expect, tap } from '@git.zone/tstest/tapbundle';
import { YardianClient, YardianConfigFlow, YardianIntegration, YardianMapper, createYardianDiscoveryDescriptor, type IYardianSnapshot } from '../../ts/integrations/yardian/index.js';

const rawData = {
  "watering": false,
  "program": "morning",
  "zones": 8
};

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

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

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

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

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

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

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

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

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

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