import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ElvClient, ElvConfigFlow, ElvIntegration, ElvMapper, HomeAssistantElvIntegration, createElvDiscoveryDescriptor, elvProfile, type IElvSnapshot } from '../../ts/integrations/elv/index.js';

const rawData = {
  device: {
    id: 'pca-301-1',
    name: 'PCA 301 Test Plug',
  },
  entities: [
    { id: 'pca_301_1', name: 'PCA 301 1', platform: 'switch', state: true },
  ],
};

tap.test('matches manual ELV PCA candidates and creates config flow output', async () => {
  const descriptor = createElvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'elv-manual-match');
  const result = await matcher!.matches({ name: 'ELV PCA 301', metadata: { rawData, device: '/dev/ttyUSB0' } }, {});

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

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

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

tap.test('maps ELV PCA raw snapshots to runtime devices and entities', async () => {
  const client = new ElvClient({ name: 'ELV Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const devices = ElvMapper.toDevices(snapshot);
  const entities = ElvMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('elv');
  expect(devices[0].manufacturer).toEqual('ELV');
  expect(entities[0].platform).toEqual('switch');
});

tap.test('exposes ELV runtime services, HA alias, and executor-gated controls', async () => {
  const integration = new ElvIntegration();
  const alias = new HomeAssistantElvIntegration();
  expect(alias.domain).toEqual('elv');
  expect(integration.status).toEqual('control-runtime');
  expect(elvProfile.metadata.qualityScale).toEqual('legacy');
  expect(elvProfile.metadata.requirements).toEqual(['pypca==0.0.7']);

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

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

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

export default tap.start();
