import { expect, tap } from '@git.zone/tstest/tapbundle';
import { WebminClient, WebminConfigFlow, WebminIntegration, WebminMapper, createWebminDiscoveryDescriptor, type IWebminSnapshot } from '../../ts/integrations/webmin/index.js';

const rawData = {
  "load": 0.42,
  "updates": 3,
  "reachable": true
};

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

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

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

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

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

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

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

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

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

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