import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ManualMqttClient, ManualMqttConfigFlow, ManualMqttIntegration, ManualMqttMapper, createManualMqttDiscoveryDescriptor, manualMqttProfile, type IManualMqttSnapshot, type TManualMqttRawData } from '../../ts/integrations/manual_mqtt/index.js';

const rawData: TManualMqttRawData = {
  device: {
    id: 'manual_mqtt-device-1',
    name: "Manual MQTT Alarm Control Panel Device",
    manufacturer: "Manual MQTT Alarm Control Panel",
    model: "Manual MQTT Alarm Control Panel local integration",
    serialNumber: 'manual_mqtt-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "manual_mqtt" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

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

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

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

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

tap.test('maps Manual MQTT Alarm Control Panel raw snapshots to runtime devices and entities', async () => {
  const client = new ManualMqttClient({ name: "Manual MQTT Alarm Control Panel Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = ManualMqttMapper.toSnapshotFromRaw({ name: "Manual MQTT Alarm Control Panel Runtime" }, rawData);
  const devices = ManualMqttMapper.toDevices(mappedSnapshot);
  const entities = ManualMqttMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("manual_mqtt");
  expect(devices[0].manufacturer).toEqual("Manual MQTT Alarm Control Panel");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "manual_mqtt" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('exposes Manual MQTT Alarm Control Panel runtime and unsupported control without executor', async () => {
  const integration = new ManualMqttIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(manualMqttProfile.metadata.configFlow).toEqual(false);
  expect(manualMqttProfile.metadata.dependencies).toEqual([
    "mqtt",
  ]);

  const runtime = await integration.setup({ name: "Manual MQTT Alarm Control Panel Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "manual_mqtt", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "manual_mqtt", service: 'refresh', target: {} });
  const snapshot = statusResult.data as IManualMqttSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Manual MQTT Alarm Control Panel Device");

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