import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LeaoneClient, LeaoneConfigFlow, LeaoneIntegration, LeaoneMapper, createLeaoneDiscoveryDescriptor, leaoneProfile, type ILeaoneSnapshot, type TLeaoneRawData } from '../../ts/integrations/leaone/index.js';

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

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

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

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

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

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

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

tap.test('exposes LeaOne runtime and unsupported control without executor', async () => {
  const integration = new LeaoneIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(leaoneProfile.metadata.configFlow).toEqual(true);
  expect(leaoneProfile.metadata.requirements).toEqual([
    "leaone-ble==0.3.0",
  ]);
  expect((leaoneProfile.metadata.localApi as { status: string }).status).toContain('leaone-ble');
  expect(((leaoneProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported).some((itemArg) => itemArg.includes('BLE scanning'))).toBeTrue();

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

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

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