import { expect, tap } from '@git.zone/tstest/tapbundle';
import { InelsClient, InelsConfigFlow, InelsIntegration, InelsMapper, createInelsDiscoveryDescriptor, inelsProfile, type IInelsSnapshot, type TInelsRawData } from '../../ts/integrations/inels/index.js';

const rawData: TInelsRawData = {
  device: {
    id: 'inels-device-1',
    name: "iNELS Device",
    manufacturer: "iNELS",
    model: "iNELS local integration",
    serialNumber: 'inels-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "switch", state: true, attributes: { domain: "inels" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual iNELS candidates and creates config flow output', async () => {
  const descriptor = createInelsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'inels-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'inels-device-1', name: "iNELS Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("inels");

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

  const done = await (await new InelsConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('inels-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps iNELS raw snapshots to runtime devices and entities', async () => {
  const client = new InelsClient({ name: "iNELS Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = InelsMapper.toSnapshotFromRaw({ name: "iNELS Runtime" }, rawData);
  const devices = InelsMapper.toDevices(mappedSnapshot);
  const entities = InelsMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("inels");
  expect(devices[0].manufacturer).toEqual("iNELS");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "inels" && entityArg.platform === "switch")).toBeTrue();
});

tap.test('exposes iNELS runtime and unsupported control without executor', async () => {
  const integration = new InelsIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(inelsProfile.metadata.configFlow).toEqual(true);
  expect(inelsProfile.metadata.requirements).toEqual([
    "elkoep-aio-mqtt==0.1.0b4",
  ]);
  expect((inelsProfile.metadata.localApi as Record<string, unknown>).status).toContain('MQTT broker semantics');
  expect(((inelsProfile.metadata.localApi as Record<string, unknown>).explicitUnsupported as string[])[0]).toContain('elkoep-aio-mqtt/inelsmqtt');

  const runtime = await integration.setup({ name: "iNELS Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "inels", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "inels", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IInelsSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("iNELS Device");

  const command = await runtime.callService!({ domain: "inels", service: inelsProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
