import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MelnorClient, MelnorConfigFlow, MelnorIntegration, MelnorMapper, createMelnorDiscoveryDescriptor, melnorProfile, type IMelnorSnapshot, type TMelnorRawData } from '../../ts/integrations/melnor/index.js';

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

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

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

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

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

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

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

tap.test('exposes Melnor Bluetooth runtime and unsupported control without executor', async () => {
  const integration = new MelnorIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(melnorProfile.metadata.configFlow).toEqual(true);
  expect(melnorProfile.metadata.requirements).toEqual([
    "melnor-bluetooth==0.0.25",
  ]);
  expect(JSON.stringify(melnorProfile.metadata.localApi)).toContain('Bluetooth Low Energy');

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

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

  const command = await runtime.callService!({ domain: "melnor", service: melnorProfile.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();
