import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ImeonInverterClient, ImeonInverterConfigFlow, ImeonInverterIntegration, ImeonInverterMapper, createImeonInverterDiscoveryDescriptor, imeonInverterProfile, type IImeonInverterSnapshot, type TImeonInverterRawData } from '../../ts/integrations/imeon_inverter/index.js';

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

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

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

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

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

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

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

tap.test('exposes Imeon Inverter runtime and unsupported control without executor', async () => {
  const integration = new ImeonInverterIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(imeonInverterProfile.metadata.configFlow).toEqual(true);
  expect(imeonInverterProfile.metadata.requirements).toEqual([
    "imeon_inverter_api==0.4.0",
  ]);

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

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

  const command = await runtime.callService!({ domain: "imeon_inverter", service: imeonInverterProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('select_option requires config.host/config.url plus config.username and config.password');
  await runtime.destroy();
});

export default tap.start();
