import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNessAlarmIntegration, NessAlarmClient, NessAlarmConfigFlow, NessAlarmIntegration, NessAlarmMapper, createNessAlarmDiscoveryDescriptor, nessAlarmProfile, type INessAlarmSnapshot, type TNessAlarmRawData } from '../../ts/integrations/ness_alarm/index.js';

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

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

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

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

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

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

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

tap.test('exposes Ness Alarm runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NessAlarmIntegration();
  const alias = new HomeAssistantNessAlarmIntegration();
  expect(alias instanceof NessAlarmIntegration).toBeTrue();
  expect(alias.domain).toEqual("ness_alarm");
  expect(integration.status).toEqual("control-runtime");
  expect(nessAlarmProfile.metadata.configFlow).toEqual(true);
  expect(nessAlarmProfile.metadata.requirements).toEqual([
    "nessclient==1.3.1",
  ]);
  expect((nessAlarmProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('nessclient==1.3.1') && itemArg.includes('IP232 TCP'))).toBeTrue();
  expect((nessAlarmProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('pyserial_asyncio_fast'))).toBeTrue();

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

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

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