import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LoqedClient, LoqedConfigFlow, LoqedIntegration, LoqedMapper, createLoqedDiscoveryDescriptor, loqedProfile, type ILoqedSnapshot, type TLoqedRawData } from '../../ts/integrations/loqed/index.js';

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

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

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

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

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

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

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

tap.test('exposes LOQED Touch Smart Lock runtime and unsupported control without executor', async () => {
  const integration = new LoqedIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(loqedProfile.metadata.configFlow).toEqual(true);
  expect(loqedProfile.metadata.requirements).toEqual([
    "loqedAPI==2.1.11",
  ]);

  const runtime = await integration.setup({ name: "LOQED Touch Smart Lock Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "loqed", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "loqed", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILoqedSnapshot;

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

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