import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHusqvarnaAutomowerBleIntegration, HusqvarnaAutomowerBleClient, HusqvarnaAutomowerBleConfigFlow, HusqvarnaAutomowerBleIntegration, HusqvarnaAutomowerBleMapper, createHusqvarnaAutomowerBleDiscoveryDescriptor, husqvarnaAutomowerBleProfile, type IHusqvarnaAutomowerBleSnapshot, type THusqvarnaAutomowerBleRawData } from '../../ts/integrations/husqvarna_automower_ble/index.js';

const rawData: THusqvarnaAutomowerBleRawData = {
  device: {
    id: 'husqvarna-aa-bb-cc-dd-ee-ff',
    name: 'Garden Automower',
    manufacturer: 'Husqvarna',
    model: 'Automower 430X',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
    protocol: 'local',
  },
  entities: [
    { id: 'activity', name: 'Mower activity', platform: 'sensor', state: 'mowing' },
    { id: 'state', name: 'Mower state', platform: 'sensor', state: 'in_operation' },
    { id: 'battery_level', name: 'Battery level', platform: 'sensor', state: 82, unit: '%', deviceClass: 'battery', stateClass: 'measurement' },
  ],
  mower: {
    activity: 'mowing',
    state: 'in_operation',
  },
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('husqvarna_automower_ble');
  expect(devices[0].manufacturer).toEqual('Husqvarna');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.garden_automower_activity')).toBeTrue();
  expect(entities.find((entityArg) => entityArg.id === 'sensor.garden_automower_battery_level')?.state).toEqual(82);
});

tap.test('exposes Husqvarna Automower BLE read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HusqvarnaAutomowerBleIntegration();
  const alias = new HomeAssistantHusqvarnaAutomowerBleIntegration();
  expect(alias instanceof HusqvarnaAutomowerBleIntegration).toBeTrue();
  expect(alias.domain).toEqual('husqvarna_automower_ble');
  expect(integration.status).toEqual('read-only-runtime');
  expect(husqvarnaAutomowerBleProfile.metadata.configFlow).toEqual(true);
  expect(husqvarnaAutomowerBleProfile.metadata.qualityScale).toEqual(undefined);
  expect(husqvarnaAutomowerBleProfile.metadata.dependencies).toEqual(['bluetooth_adapters']);

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

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

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

export default tap.start();
