import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EarnEP1Client, EarnEP1ConfigFlow, EarnEP1Integration, EarnEP1Mapper, HomeAssistantEarnEP1Integration, earnEP1Profile, createEarnEP1DiscoveryDescriptor, type IEarnEP1Snapshot } from '../../ts/integrations/earn_e_p1/index.js';

const rawData = {
  device: {
    id: 'earn-e-serial-1',
    name: 'EARN-E P1 Meter',
    manufacturer: 'EARN-E',
    model: 'P1 Meter',
    serialNumber: 'EARN123456',
    host: '192.0.2.20',
  },
  entities: [
    { id: 'power_delivered', name: 'Power imported', platform: 'sensor', state: 1.23, unit: 'kW', deviceClass: 'power', stateClass: 'measurement' },
    { id: 'energy_delivered_tariff1', name: 'Energy imported tariff 1', platform: 'sensor', state: 456.78, unit: 'kWh', deviceClass: 'energy', stateClass: 'total_increasing' },
    { id: 'wifiRSSI', name: 'Wi-Fi RSSI', platform: 'sensor', state: -61, unit: 'dBm', deviceClass: 'signal_strength' },
  ],
};

tap.test('matches manual EARN-E P1 candidates and creates config flow output', async () => {
  const descriptor = createEarnEP1DiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'earn_e_p1-manual-match');
  const result = await matcher!.matches({ host: '192.0.2.20', name: 'EARN-E P1 Meter', metadata: { rawData } }, {});

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

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

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

tap.test('maps EARN-E P1 raw snapshots to runtime devices and entities', async () => {
  const snapshot = EarnEP1Mapper.toSnapshotFromRaw({ name: 'EARN-E Test', rawData }, rawData);
  const devices = EarnEP1Mapper.toDevices(snapshot);
  const entities = EarnEP1Mapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('earn_e_p1');
  expect(devices[0].manufacturer).toEqual('EARN-E');
  expect(entities.length).toEqual(3);
  expect(entities.some((entityArg) => entityArg.attributes?.deviceClass === 'energy')).toBeTrue();
});

tap.test('exposes EARN-E P1 read-only runtime and unsupported controls', async () => {
  expect(new HomeAssistantEarnEP1Integration().domain).toEqual('earn_e_p1');
  expect(earnEP1Profile.status).toEqual('read-only-runtime');
  expect(earnEP1Profile.metadata.qualityScale).toEqual('bronze');
  expect(earnEP1Profile.metadata.requirements).toEqual(['earn-e-p1==0.1.0']);

  const client = new EarnEP1Client({ name: 'EARN-E Client', rawData });
  expect((await client.getSnapshot()).source).toEqual('manual');

  const runtime = await new EarnEP1Integration().setup({ name: 'EARN-E Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'earn_e_p1', service: 'status', target: {} });
  const snapshot = status.data as IEarnEP1Snapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('EARN-E P1 Meter');

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

export default tap.start();
