import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MedcomBleClient, MedcomBleConfigFlow, MedcomBleIntegration, MedcomBleMapper, createMedcomBleDiscoveryDescriptor, medcomBleProfile, type IMedcomBleSnapshot, type TMedcomBleRawData } from '../../ts/integrations/medcom_ble/index.js';

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

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("medcom_ble");
  expect(devices[0].manufacturer).toEqual("Medcom Bluetooth");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "medcom_ble" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('exposes Medcom Bluetooth runtime and unsupported control without executor', async () => {
  const integration = new MedcomBleIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(medcomBleProfile.metadata.configFlow).toEqual(true);
  expect(medcomBleProfile.metadata.requirements).toEqual([
    "medcom-ble==0.1.1",
  ]);

  const runtime = await integration.setup({ name: "Medcom Bluetooth Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "medcom_ble", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "medcom_ble", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IMedcomBleSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeFalse();
  expect(refresh.error!).toContain('Medcom BLE refresh requires an injected BLE client');
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Medcom Bluetooth Device");

  const command = await runtime.callService!({ domain: "medcom_ble", service: medcomBleProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('Medcom BLE is read-only');
  await runtime.destroy();
});

export default tap.start();
