import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMopekaIntegration, MopekaClient, MopekaConfigFlow, MopekaIntegration, MopekaMapper, createMopekaDiscoveryDescriptor, mopekaProfile, type IMopekaSnapshot, type TMopekaRawData } from '../../ts/integrations/mopeka/index.js';

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

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

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

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

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

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

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

tap.test('exposes Mopeka runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MopekaIntegration();
  const alias = new HomeAssistantMopekaIntegration();
  expect(alias instanceof MopekaIntegration).toBeTrue();
  expect(alias.domain).toEqual("mopeka");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mopekaProfile.metadata.configFlow).toEqual(true);
  expect(mopekaProfile.metadata.requirements).toEqual([
    "mopeka-iot-ble==0.8.0",
  ]);
  expect((mopekaProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((entryArg) => entryArg.includes('passive Bluetooth'))).toBeTrue();

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

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

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