import { expect, tap } from '@git.zone/tstest/tapbundle';
import { VeluxClient, VeluxConfigFlow, VeluxIntegration, VeluxMapper, createVeluxDiscoveryDescriptor, type IVeluxSnapshot } from '../../ts/integrations/velux/index.js';

const rawData = {
  "covers": 4,
  "gateway": "online",
  "battery_low": false
};

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

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

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

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

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

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

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

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

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

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

export default tap.start();
