import { expect, tap } from '@git.zone/tstest/tapbundle';
import { BboxClient, BboxConfigFlow, BboxIntegration, BboxMapper, HomeAssistantBboxIntegration, bboxProfile, createBboxDiscoveryDescriptor, type IBboxSnapshot } from '../../ts/integrations/bbox/index.js';

const rawData = {
  clients: 9,
  wan_up: true,
  uptime: 123456
};

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

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

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

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

tap.test('maps Bbox raw snapshots to router devices and sensor entities', async () => {
  const client = new BboxClient({ name: 'Bbox Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = BboxMapper.toDevices(snapshot);
  const entities = BboxMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(snapshot.entities.find((entityArg) => entityArg.id === 'wan_up')?.platform).toEqual('binary_sensor');
  expect(snapshot.entities.find((entityArg) => entityArg.id === 'clients')?.state).toEqual(9);
  expect(devices[0].manufacturer).toEqual('Bouygues Telecom');
  expect(entities.length).toEqual(3);
});

tap.test('exposes Bbox read-only runtime services and preserves Home Assistant alias', async () => {
  const integration = new HomeAssistantBboxIntegration();
  expect(integration).toBeInstanceOf(BboxIntegration);
  expect(integration.status).toEqual('read-only-runtime');
  expect(bboxProfile.controlServices).toEqual([]);
  expect((bboxProfile.metadata.runtime as { controls: boolean }).controls).toBeFalse();

  const runtime = await integration.setup({ name: 'Bbox Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'bbox', service: 'status', target: {} });
  const snapshot = status.data as IBboxSnapshot;

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

  const unsupportedDomain = await runtime.callService!({ domain: 'media_player', service: 'media_play', target: {} });
  expect(unsupportedDomain.success).toBeFalse();
  await runtime.destroy();
});

export default tap.start();
