import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AltruistClient, AltruistConfigFlow, AltruistIntegration, AltruistMapper, createAltruistDiscoveryDescriptor, type IAltruistSnapshot } from '../../ts/integrations/altruist/index.js';

const rawData = {
  "score": 72,
  "trend": "stable",
  "online": true
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('altruist');
  expect(entities.find((entityArg) => entityArg.name === 'Score')?.state).toEqual(72);
  expect(entities.find((entityArg) => entityArg.name === 'Online')?.platform).toEqual('binary_sensor');
});

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

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

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

export default tap.start();
