import { expect, tap } from '@git.zone/tstest/tapbundle';
import { IdasenDeskClient, IdasenDeskConfigFlow, IdasenDeskIntegration, IdasenDeskMapper, HomeAssistantIdasenDeskIntegration, createIdasenDeskDiscoveryDescriptor, idasenDeskProfile, idasenDeskServiceUuid, type IIdasenDeskSnapshot, type TIdasenDeskRawData } from '../../ts/integrations/idasen_desk/index.js';

const rawData: TIdasenDeskRawData = {
  device: {
    id: 'idasen-AA:BB:CC:DD:EE:FF',
    name: 'Bedroom Desk',
    manufacturer: 'LINAK',
    model: 'IKEA Idasen Desk',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
    attributes: {
      address: 'AA:BB:CC:DD:EE:FF',
      serviceUuid: idasenDeskServiceUuid,
    },
  },
  entities: [
    { id: 'desk', name: 'Desk', platform: 'cover', state: 'open', writable: true, attributes: { currentPosition: 72, supportedFeatures: ['open', 'close', 'stop', 'set_position'] } },
    { id: 'height', name: 'Height', platform: 'sensor', state: 1.13, unit: 'm', deviceClass: 'distance', stateClass: 'measurement' },
    { id: 'connect', name: 'Connect', platform: 'button', state: 'idle', writable: true, attributes: { category: 'config' } },
    { id: 'disconnect', name: 'Disconnect', platform: 'button', state: 'idle', writable: true, attributes: { category: 'config' } },
  ],
};

tap.test('matches manual Idasen Desk candidates and creates config flow output', async () => {
  const descriptor = createIdasenDeskDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'idasen_desk-manual-match');
  const result = await matcher!.matches({ id: 'AA:BB:CC:DD:EE:FF', name: 'Bedroom Idasen Desk', metadata: { address: 'AA:BB:CC:DD:EE:FF', serviceUuid: idasenDeskServiceUuid, rawData } }, {});

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

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

  const done = await (await new IdasenDeskConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('AA:BB:CC:DD:EE:FF');
  expect(done.config?.metadata?.serviceUuid).toEqual(idasenDeskServiceUuid);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('idasen_desk');
  expect(devices[0].manufacturer).toEqual('LINAK');
  expect(entities.some((entityArg) => entityArg.id === 'cover.bedroom_desk_desk')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'sensor.bedroom_desk_height')).toBeTrue();
});

tap.test('exposes Idasen Desk read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new IdasenDeskIntegration();
  const alias = new HomeAssistantIdasenDeskIntegration();
  expect(alias instanceof IdasenDeskIntegration).toBeTrue();
  expect(alias.domain).toEqual('idasen_desk');
  expect(integration.status).toEqual('read-only-runtime');
  expect(idasenDeskProfile.metadata.configFlow).toEqual(true);
  expect(idasenDeskProfile.metadata.qualityScale).toEqual('bronze');
  expect(idasenDeskProfile.metadata.requirements).toEqual(['idasen-ha==2.6.5']);

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

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

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

export default tap.start();
