import { expect, tap } from '@git.zone/tstest/tapbundle';
import { TransmissionClient, TransmissionConfigFlow, TransmissionIntegration, TransmissionMapper, createTransmissionDiscoveryDescriptor, type ITransmissionSnapshot } from '../../ts/integrations/transmission/index.js';

const rawData = {
  "active_torrents": 2,
  "download_speed": 1024,
  "turtle_mode": false
};

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

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

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

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

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

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

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

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

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

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