import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KostalPlenticoreClient, KostalPlenticoreConfigFlow, KostalPlenticoreIntegration, KostalPlenticoreMapper, createKostalPlenticoreDiscoveryDescriptor, kostalPlenticoreProfile, type IKostalPlenticoreSnapshot, type TKostalPlenticoreRawData } from '../../ts/integrations/kostal_plenticore/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("kostal_plenticore");
  expect(devices[0].manufacturer).toEqual("Kostal Plenticore Solar Inverter");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "kostal_plenticore" && entityArg.platform === "number")).toBeTrue();
});

tap.test('exposes Kostal Plenticore Solar Inverter runtime and unsupported control without executor', async () => {
  const integration = new KostalPlenticoreIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(kostalPlenticoreProfile.metadata.configFlow).toEqual(true);
  expect(kostalPlenticoreProfile.metadata.requirements).toEqual([
    "pykoplenti==1.5.0",
  ]);

  const runtime = await integration.setup({ name: "Kostal Plenticore Solar Inverter Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "kostal_plenticore", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "kostal_plenticore", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IKostalPlenticoreSnapshot;

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

  const command = await runtime.callService!({ domain: "kostal_plenticore", service: kostalPlenticoreProfile.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();
