import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GardenaBluetoothClient, GardenaBluetoothConfigFlow, GardenaBluetoothIntegration, GardenaBluetoothMapper, HomeAssistantGardenaBluetoothIntegration, createGardenaBluetoothDiscoveryDescriptor, gardenaBluetoothProfile, gardenaBluetoothServiceUuid, type IGardenaBluetoothSnapshot, type TGardenaBluetoothRawData } from '../../ts/integrations/gardena_bluetooth/index.js';

const rawData: TGardenaBluetoothRawData = {
  device: {
    id: 'gardena-aa-bb-cc-dd-ee-ff',
    name: 'Gardena Valve',
    manufacturer: 'Gardena',
    model: 'Water Computer Bluetooth',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
  },
  entities: [
    { id: 'valve_connected_state', name: 'Valve Connection', platform: 'binary_sensor', state: true, deviceClass: 'connectivity' },
    { id: 'battery_level', name: 'Battery Level', platform: 'sensor', state: 87, unit: '%', deviceClass: 'battery' },
    { id: 'manual_watering_time', name: 'Manual Watering Time', platform: 'number', state: 900, writable: true, unit: 's', deviceClass: 'duration' },
    { id: 'valve', name: 'Valve', platform: 'switch', state: false, writable: true, deviceClass: 'water', attributes: { remainingOpenTime: 0 } },
    { id: 'operation_mode', name: 'Operation Mode', platform: 'select', state: 'active', writable: true, attributes: { options: ['active', 'manual_mode', 'deep_sleep'] } },
    { id: 'custom_device_name', name: 'Custom Device Name', platform: 'text', state: 'Front Garden', writable: true },
    { id: 'factory_reset', name: 'Factory Reset', platform: 'button', state: 'ready', writable: true },
  ],
};

tap.test('matches manual Gardena Bluetooth candidates and creates config flow output', async () => {
  const descriptor = createGardenaBluetoothDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'gardena_bluetooth-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'AA:BB:CC:DD:EE:FF', name: 'Gardena Valve', metadata: { rawData, serviceUuid: gardenaBluetoothServiceUuid } }, {});

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

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

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

tap.test('maps Gardena Bluetooth raw snapshots to runtime devices and entities', async () => {
  const client = new GardenaBluetoothClient({ name: 'Gardena Valve', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = GardenaBluetoothMapper.toSnapshotFromRaw({ name: 'Gardena Valve' }, rawData);
  const devices = GardenaBluetoothMapper.toDevices(mappedSnapshot);
  const entities = GardenaBluetoothMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('gardena_bluetooth');
  expect(devices[0].manufacturer).toEqual('Gardena');
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.gardena_valve_valve_connected_state')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.gardena_valve_valve')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'number.gardena_valve_manual_watering_time')).toBeTrue();
});

tap.test('exposes Gardena Bluetooth read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GardenaBluetoothIntegration();
  const alias = new HomeAssistantGardenaBluetoothIntegration();
  expect(alias instanceof GardenaBluetoothIntegration).toBeTrue();
  expect(alias.domain).toEqual('gardena_bluetooth');
  expect(integration.status).toEqual('read-only-runtime');
  expect(gardenaBluetoothProfile.metadata.configFlow).toEqual(true);
  expect(gardenaBluetoothProfile.metadata.dependencies).toEqual(['bluetooth_adapters']);
  expect(gardenaBluetoothProfile.metadata.requirements).toEqual(['gardena-bluetooth==2.4.0']);

  const runtime = await integration.setup({ name: 'Gardena Valve', rawData }, {});
  const status = await runtime.callService!({ domain: 'gardena_bluetooth', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'gardena_bluetooth', service: 'refresh', target: {} });
  const snapshot = status.data as IGardenaBluetoothSnapshot;

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

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

export default tap.start();
