import { expect, tap } from '@git.zone/tstest/tapbundle';
import { CppmTrackerClient, CppmTrackerConfigFlow, CppmTrackerIntegration, CppmTrackerMapper, HomeAssistantCppmTrackerIntegration, cppmTrackerProfile, createCppmTrackerDiscoveryDescriptor, type ICppmTrackerSnapshot } from '../../ts/integrations/cppm_tracker/index.js';

const rawData = {
  endpoints: 42,
  authenticated: 40,
  online: true,
};

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

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

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

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

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

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

tap.test('exposes Aruba ClearPass read-only runtime without control services', async () => {
  expect(new HomeAssistantCppmTrackerIntegration().domain).toEqual('cppm_tracker');
  expect(cppmTrackerProfile.status).toEqual('read-only-runtime');
  expect(cppmTrackerProfile.metadata.qualityScale).toEqual('legacy');
  expect(cppmTrackerProfile.metadata.requirements).toEqual(['clearpasspy==1.0.2']);

  const runtime = await new CppmTrackerIntegration().setup({ name: 'Aruba ClearPass Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'cppm_tracker', service: 'status', target: {} });
  const snapshot = status.data as ICppmTrackerSnapshot;

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

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

export default tap.start();
