import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIdteckProxIntegration, IdteckProxClient, IdteckProxConfigFlow, IdteckProxIntegration, IdteckProxMapper, createIdteckProxDiscoveryDescriptor, idteckProxProfile, type IIdteckProxSnapshot, type TIdteckProxRawData } from '../../ts/integrations/idteck_prox/index.js';

const rawData: TIdteckProxRawData = {
  device: {
    id: 'idteck-front-door',
    name: 'Front Door Reader',
    manufacturer: 'IDTECK',
    model: 'RFK101 proximity reader',
    host: '192.0.2.11',
    port: 9000,
    protocol: 'tcp',
  },
  entities: [
    { id: 'last_card', name: 'Last Card', platform: 'sensor', state: '1234567890', attributes: { event: 'idteck_prox_keycard' } },
    { id: 'reader_name', name: 'Reader Name', platform: 'sensor', state: 'Front Door Reader' },
    { id: 'event_count', name: 'Event Count', platform: 'sensor', state: 7, stateClass: 'measurement' },
    { id: 'connected', name: 'Connected', platform: 'binary_sensor', state: true, deviceClass: 'connectivity' },
  ],
};

tap.test('matches manual IDTECK Prox candidates and creates config flow output', async () => {
  const descriptor = createIdteckProxDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'idteck_prox-manual-match');
  const result = await matcher!.matches({ id: 'front-door-reader', host: '192.0.2.11', port: 9000, name: 'Front Door Reader', metadata: { rawData } }, {});

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

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

  const done = await (await new IdteckProxConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.0.2.11');
  expect(done.config?.port).toEqual(9000);
});

tap.test('maps IDTECK Prox raw snapshots to runtime devices and entities', async () => {
  const client = new IdteckProxClient({ name: 'IDTECK Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = IdteckProxMapper.toSnapshotFromRaw({ name: 'IDTECK Runtime' }, rawData);
  const devices = IdteckProxMapper.toDevices(mappedSnapshot);
  const entities = IdteckProxMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('idteck_prox');
  expect(devices[0].manufacturer).toEqual('IDTECK');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.front_door_reader_last_card')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.front_door_reader_connected')).toBeTrue();
});

tap.test('exposes IDTECK Prox read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new IdteckProxIntegration();
  const alias = new HomeAssistantIdteckProxIntegration();
  expect(alias instanceof IdteckProxIntegration).toBeTrue();
  expect(alias.domain).toEqual('idteck_prox');
  expect(integration.status).toEqual('read-only-runtime');
  expect(idteckProxProfile.metadata.configFlow).toEqual(false);
  expect(idteckProxProfile.metadata.qualityScale).toEqual('legacy');
  expect(idteckProxProfile.metadata.requirements).toEqual(['rfk101py==0.0.1']);

  const runtime = await integration.setup({ name: 'IDTECK Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'idteck_prox', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'idteck_prox', service: 'refresh', target: {} });
  const snapshot = status.data as IIdteckProxSnapshot;

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

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