import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FjaraskupanClient, FjaraskupanConfigFlow, FjaraskupanIntegration, FjaraskupanMapper, HomeAssistantFjaraskupanIntegration, createFjaraskupanDiscoveryDescriptor, fjaraskupanProfile, type IFjaraskupanSnapshot, type TFjaraskupanRawData } from '../../ts/integrations/fjaraskupan/index.js';

const rawData: TFjaraskupanRawData = {
  device: {
    id: 'fjaraskupan-aa-bb',
    name: 'Fjaraskupan Kitchen',
    manufacturer: 'Fjaraskupan',
    model: 'Bluetooth cooker hood',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
  },
  entities: [
    { id: 'fan', name: 'Fan', platform: 'fan', state: 50, writable: true, attributes: { presetMode: 'normal', speedCount: 8 } },
    { id: 'light', name: 'Light', platform: 'light', state: true, writable: true, attributes: { brightness: 191 } },
    { id: 'periodic_venting', name: 'Periodic Venting', platform: 'number', state: 15, writable: true, unit: 'min', attributes: { min: 0, max: 59, step: 1 } },
    { id: 'rssi', name: 'Signal Strength', platform: 'sensor', state: -62, unit: 'dBm', deviceClass: 'signal_strength' },
    { id: 'grease_filter', name: 'Grease Filter', platform: 'binary_sensor', state: false, deviceClass: 'problem' },
    { id: 'carbon_filter', name: 'Carbon Filter', platform: 'binary_sensor', state: true, deviceClass: 'problem' },
  ],
  state: {
    fan_speed: 4,
    light_on: true,
    periodic_venting: 15,
  },
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('fjaraskupan');
  expect(devices[0].manufacturer).toEqual('Fjaraskupan');
  expect(entities.some((entityArg) => entityArg.id === 'fan.fjaraskupan_kitchen_fan')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.fjaraskupan_kitchen_carbon_filter')).toBeTrue();
});

tap.test('exposes Fjaraskupan read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FjaraskupanIntegration();
  const alias = new HomeAssistantFjaraskupanIntegration();
  expect(alias instanceof FjaraskupanIntegration).toBeTrue();
  expect(alias.domain).toEqual('fjaraskupan');
  expect(integration.status).toEqual('read-only-runtime');
  expect(fjaraskupanProfile.metadata.configFlow).toEqual(true);
  expect(fjaraskupanProfile.metadata.requirements).toEqual(['fjaraskupan==2.3.3']);
  expect(fjaraskupanProfile.metadata.dependencies).toEqual(['bluetooth_adapters']);

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

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

  const command = await runtime.callService!({ domain: 'fan', service: 'turn_on', target: { entityId: 'fan.fjaraskupan_runtime_fan' }, data: { percentage: 50 } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
