import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EnvisalinkClient, EnvisalinkConfigFlow, EnvisalinkIntegration, EnvisalinkMapper, HomeAssistantEnvisalinkIntegration, createEnvisalinkDiscoveryDescriptor, envisalinkProfile, type IEnvisalinkSnapshot } from '../../ts/integrations/envisalink/index.js';

const rawData = {
  device: {
    id: 'envisalink-panel-1',
    name: 'Envisalink Alarm Panel',
    manufacturer: 'EyezOn',
    model: 'EVL-4',
  },
  entities: [
    { id: 'partition_1_keypad', name: 'Partition 1 Keypad', platform: 'sensor', state: 'Ready', attributes: { armedAway: false, alarm: false } },
    { id: 'front_door', name: 'Front Door', platform: 'binary_sensor', state: false, deviceClass: 'opening', attributes: { zone: 1 } },
    { id: 'front_door_bypass', name: 'Front Door Bypass', platform: 'switch', state: false, writable: true, attributes: { zone: 1 } },
  ],
};

tap.test('matches manual Envisalink candidates and creates config flow output', async () => {
  const descriptor = createEnvisalinkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'envisalink-manual-match');
  const result = await matcher!.matches({ host: 'envisalink.local', name: 'Envisalink', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('envisalink');
  expect(result.candidate?.port).toEqual(4025);

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

  const done = await (await new EnvisalinkConfigFlow().start(result.candidate!, {})).submit!({ username: 'user', password: 'secret' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('envisalink.local');
  expect(done.config?.port).toEqual(4025);
  expect(done.config?.transport).toEqual('tcp');
});

tap.test('maps Envisalink raw snapshots to runtime devices and entities', async () => {
  const client = new EnvisalinkClient({ name: 'Envisalink Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EnvisalinkMapper.toDevices(snapshot);
  const entities = EnvisalinkMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('envisalink');
  expect(devices[0].manufacturer).toEqual('EyezOn');
  expect(entities.length).toEqual(3);
});

tap.test('exposes Envisalink runtime services, HA alias, and unsupported control without executor', async () => {
  const integration = new EnvisalinkIntegration();
  const alias = new HomeAssistantEnvisalinkIntegration();
  expect(alias instanceof EnvisalinkIntegration).toBeTrue();
  expect(alias.domain).toEqual('envisalink');
  expect(integration.status).toEqual('control-runtime');
  expect(envisalinkProfile.metadata.requirements).toEqual(['pyenvisalink==4.7']);
  expect(envisalinkProfile.metadata.configFlow).toEqual(false);

  const runtime = await integration.setup({ name: 'Envisalink Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'envisalink', service: 'status', target: {} });
  const snapshot = status.data as IEnvisalinkSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Envisalink Alarm Panel');
  expect((await runtime.callService!({ domain: 'envisalink', service: 'refresh', target: {} })).success).toBeTrue();

  const command = await runtime.callService!({ domain: 'alarm_control_panel', service: 'alarm_arm_away', target: {}, data: { code: '1234' } });
  expect(command.success).toBeFalse();
  expect(command.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
