import { expect, tap } from '@git.zone/tstest/tapbundle';
import { WatergateClient, WatergateConfigFlow, WatergateIntegration, WatergateMapper, createWatergateDiscoveryDescriptor, type IWatergateSnapshot } from '../../ts/integrations/watergate/index.js';

const rawData = {
  "watering": false,
  "zones": 6,
  "flow": 0
};

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

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

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

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

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

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

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

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

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

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