import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KegtronClient, KegtronConfigFlow, KegtronIntegration, KegtronMapper, createKegtronDiscoveryDescriptor, kegtronProfile, type IKegtronSnapshot, type TKegtronRawData } from '../../ts/integrations/kegtron/index.js';

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

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

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

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

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

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

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

tap.test('exposes Kegtron runtime and unsupported control without executor', async () => {
  const integration = new KegtronIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(kegtronProfile.metadata.configFlow).toEqual(true);
  expect(kegtronProfile.metadata.requirements).toEqual([
    "kegtron-ble==1.0.2",
  ]);
  expect((kegtronProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('no BLE scanner stack'))).toBeTrue();

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

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

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