import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EdimaxClient, EdimaxConfigFlow, EdimaxIntegration, EdimaxMapper, HomeAssistantEdimaxIntegration, createEdimaxDiscoveryDescriptor, edimaxProfile, type IEdimaxSnapshot } from '../../ts/integrations/edimax/index.js';

const rawData = {
  info: {
    mac: 'AA:BB:CC:DD:EE:FF',
  },
  state: 'ON',
};

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

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

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

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

tap.test('maps Edimax raw snapshots to switch devices and entities', async () => {
  const client = new EdimaxClient({ name: 'Kitchen Plug', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EdimaxMapper.toDevices(snapshot);
  const entities = EdimaxMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('edimax');
  expect(devices[0].manufacturer).toEqual('Edimax');
  expect(devices[0].features[0].writable).toBeTrue();
  expect(entities[0].platform).toEqual('switch');
  expect(entities[0].state).toBeTrue();
});

tap.test('exposes Edimax runtime, HA alias, and explicit unsupported control without executor', async () => {
  expect(new HomeAssistantEdimaxIntegration().domain).toEqual('edimax');
  expect(edimaxProfile.status).toEqual('control-runtime');
  expect(edimaxProfile.metadata.configFlow).toEqual(false);
  expect(edimaxProfile.metadata.requirements).toEqual(['pyedimax==0.2.1']);

  const runtime = await new EdimaxIntegration().setup({ name: 'Kitchen Plug', rawData }, {});
  const status = await runtime.callService!({ domain: 'edimax', service: 'status', target: {} });
  const snapshot = status.data as IEdimaxSnapshot;

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

  const controlCommand = await runtime.callService!({ domain: 'switch', service: 'turn_off', target: {} });
  expect(controlCommand.success).toBeFalse();
  expect(controlCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
