import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIalarmIntegration, IalarmClient, IalarmConfigFlow, IalarmIntegration, IalarmMapper, createIalarmDiscoveryDescriptor, ialarmProfile, type IIalarmSnapshot, type TIalarmRawData } from '../../ts/integrations/ialarm/index.js';

const rawData: TIalarmRawData = {
  device: {
    id: 'ialarm-aa-bb-cc-dd-ee-ff',
    name: 'iAlarm',
    manufacturer: 'Antifurto365 - Meian',
    model: 'iAlarm',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
    host: '192.0.2.34',
    port: 18034,
  },
  entities: [
    { id: 'alarm_state', name: 'Alarm state', platform: 'sensor', state: 'armed_away', writable: true, attributes: { supportedFeatures: ['arm_home', 'arm_away'] } },
    { id: 'online', name: 'Online', platform: 'binary_sensor', state: true, deviceClass: 'connectivity' },
  ],
  status: 'armed_away',
};

tap.test('matches manual iAlarm candidates and creates config flow output', async () => {
  const descriptor = createIalarmDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ialarm-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'ialarm-aa-bb-cc-dd-ee-ff', name: 'Antifurto365 iAlarm', metadata: { rawData } }, {});

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

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

  const done = await (await new IalarmConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Antifurto365 iAlarm');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps iAlarm raw snapshots to runtime devices and entities', async () => {
  const client = new IalarmClient({ rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = IalarmMapper.toSnapshotFromRaw({}, rawData);
  const devices = IalarmMapper.toDevices(mappedSnapshot);
  const entities = IalarmMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('ialarm');
  expect(devices[0].manufacturer).toEqual('Antifurto365 - Meian');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.ialarm_alarm_state')).toBeTrue();
  expect(entities.find((entityArg) => entityArg.id === 'sensor.ialarm_alarm_state')?.state).toEqual('armed_away');
});

tap.test('exposes iAlarm read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new IalarmIntegration();
  const alias = new HomeAssistantIalarmIntegration();
  expect(alias instanceof IalarmIntegration).toBeTrue();
  expect(alias.domain).toEqual('ialarm');
  expect(integration.status).toEqual('read-only-runtime');
  expect(ialarmProfile.metadata.configFlow).toEqual(true);
  expect(ialarmProfile.metadata.qualityScale).toEqual(undefined);
  expect(ialarmProfile.metadata.requirements).toEqual(['pyialarm==2.2.0']);

  const runtime = await integration.setup({ rawData }, {});
  const status = await runtime.callService!({ domain: 'alarm_control_panel', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'ialarm', service: 'refresh', target: {} });
  const snapshot = status.data as IIalarmSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('iAlarm');

  const command = await runtime.callService!({ domain: 'alarm_control_panel', service: 'alarm_arm_away', target: { entityId: 'alarm_control_panel.ialarm' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
