import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMqttJsonIntegration, MqttJsonClient, MqttJsonConfigFlow, MqttJsonIntegration, MqttJsonMapper, createMqttJsonDiscoveryDescriptor, mqttJsonProfile, type IMqttJsonSnapshot, type TMqttJsonRawData } from '../../ts/integrations/mqtt_json/index.js';

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

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

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

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

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

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

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

tap.test('documents MQTT JSON broker blocker and refuses generic HTTP fallback', async () => {
  const metadata = mqttJsonProfile.metadata as {
    runtime: { blocker: string; controls: boolean };
    localApi: { status: string; explicitUnsupported: string[] };
  };
  const originalFetch = globalThis.fetch;
  let fetchCalls = 0;
  globalThis.fetch = (async () => {
    fetchCalls += 1;
    throw new Error('HTTP fallback must not be used for mqtt_json');
  }) as typeof fetch;

  try {
    const snapshot = await new MqttJsonClient({ name: 'MQTT JSON Live', host: '127.0.0.1', path: '/gps', transport: 'http' }).getSnapshot(true);
    expect(snapshot.online).toBeFalse();
    expect(snapshot.error!).toContain('mqtt.async_subscribe');

    const runtime = await new MqttJsonIntegration().setup({ name: 'MQTT JSON Runtime', host: '127.0.0.1', path: '/gps', transport: 'http' }, {});
    const status = await runtime.callService!({ domain: 'mqtt_json', service: 'status', target: {} });
    const runtimeSnapshot = status.data as IMqttJsonSnapshot;
    expect(runtimeSnapshot.online).toBeFalse();
    expect(runtimeSnapshot.error!).toContain('mqtt.async_subscribe');
    await runtime.destroy();

    expect(fetchCalls).toEqual(0);
  } finally {
    globalThis.fetch = originalFetch;
  }

  expect(metadata.runtime.controls).toBeFalse();
  expect(metadata.runtime.blocker).toContain('MQTT JSON live tracking requires');
  expect(metadata.localApi.status).toContain('MQTT broker semantics');
  expect(metadata.localApi.explicitUnsupported.some((itemArg) => itemArg.includes('mqtt.async_subscribe') && itemArg.includes('per-device topic'))).toBeTrue();
});

tap.test('exposes MQTT JSON runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MqttJsonIntegration();
  const alias = new HomeAssistantMqttJsonIntegration();
  expect(alias instanceof MqttJsonIntegration).toBeTrue();
  expect(alias.domain).toEqual("mqtt_json");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mqttJsonProfile.metadata.configFlow).toEqual(false);
  expect(mqttJsonProfile.metadata.requirements).toEqual([]);

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

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

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