import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ApacheKafkaClient, ApacheKafkaConfigFlow, ApacheKafkaIntegration, ApacheKafkaMapper, createApacheKafkaDiscoveryDescriptor, type IApacheKafkaSnapshot } from '../../ts/integrations/apache_kafka/index.js';

const rawData = {
  "brokers": 3,
  "connected": true,
  "lag": 0
};

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

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

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

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

tap.test('maps Apache Kafka raw snapshots to runtime devices and entities', async () => {
  const snapshot = ApacheKafkaMapper.toSnapshotFromRaw({ name: 'Kafka Test' }, rawData);
  const clientSnapshot = await new ApacheKafkaClient({ name: 'Kafka Test', rawData }).getSnapshot();
  const devices = ApacheKafkaMapper.toDevices(clientSnapshot);
  const entities = ApacheKafkaMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('apache_kafka');
  expect(entities.find((entityArg) => entityArg.name === 'Brokers')?.state).toEqual(3);
  expect(entities.find((entityArg) => entityArg.name === 'Connected')?.platform).toEqual('binary_sensor');
});

tap.test('exposes Apache Kafka runtime status without fake live control', async () => {
  const runtime = await new ApacheKafkaIntegration().setup({ name: 'Kafka Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'apache_kafka', service: 'status', target: {} });
  const snapshot = status.data as IApacheKafkaSnapshot;

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

  const liveCommand = await runtime.callService!({ domain: 'apache_kafka', service: 'publish', target: {}, data: { topic: 'alerts', message: 'test' } });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();

  const executorRuntime = await new ApacheKafkaIntegration().setup({
    name: 'Kafka Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service, topic: requestArg.data?.topic } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'apache_kafka', service: 'publish', target: {}, data: { topic: 'alerts', message: 'test' } });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('publish');
  expect((executed.data as { topic: string }).topic).toEqual('alerts');
  await executorRuntime.destroy();
});

export default tap.start();
