import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LedBleClient, LedBleConfigFlow, LedBleIntegration, LedBleMapper, createLedBleDiscoveryDescriptor, ledBleProfile, type ILedBleSnapshot, type TLedBleRawData } from '../../ts/integrations/led_ble/index.js';

const rawData: TLedBleRawData = {
  device: {
    id: 'led_ble-device-1',
    name: "LED BLE Device",
    manufacturer: "LED BLE",
    model: "LED BLE local integration",
    serialNumber: 'led_ble-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "light", state: true, attributes: { domain: "led_ble" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual LED BLE candidates and creates config flow output', async () => {
  const descriptor = createLedBleDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'led_ble-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'led_ble-device-1', name: "LED BLE Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("led_ble");

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

  const done = await (await new LedBleConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('led_ble-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("led_ble");
  expect(devices[0].manufacturer).toEqual("LED BLE");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "led_ble" && entityArg.platform === "light")).toBeTrue();
});

tap.test('exposes LED BLE runtime and unsupported control without executor', async () => {
  const integration = new LedBleIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(ledBleProfile.metadata.configFlow).toEqual(true);
  expect(ledBleProfile.metadata.requirements).toEqual([
    "bluetooth-data-tools==1.28.4",
    "led-ble==1.1.8",
  ]);
  expect((ledBleProfile.metadata.localApi as { status: string }).status).toContain('led-ble');
  expect(((ledBleProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported).some((itemArg) => itemArg.includes('GATT'))).toBeTrue();

  const runtime = await integration.setup({ name: "LED BLE Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "led_ble", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "led_ble", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILedBleSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("LED BLE Device");

  const command = await runtime.callService!({ domain: "led_ble", service: ledBleProfile.controlServices?.[0] || '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();
