import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMoatIntegration, MoatClient, MoatConfigFlow, MoatIntegration, MoatMapper, createMoatDiscoveryDescriptor, moatProfile, type IMoatSnapshot, type TMoatRawData } from '../../ts/integrations/moat/index.js';

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

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

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

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

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

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

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

tap.test('exposes Moat runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MoatIntegration();
  const alias = new HomeAssistantMoatIntegration();
  expect(alias instanceof MoatIntegration).toBeTrue();
  expect(alias.domain).toEqual("moat");
  expect(integration.status).toEqual("read-only-runtime");
  expect(moatProfile.metadata.configFlow).toEqual(true);
  expect(moatProfile.metadata.requirements).toEqual([
    "moat-ble==0.1.1",
  ]);
  expect((moatProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((valueArg) => valueArg.includes('PassiveBluetoothProcessorCoordinator'))).toBeTrue();

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

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

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