import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMqttRoomIntegration, MqttRoomClient, MqttRoomConfigFlow, MqttRoomIntegration, MqttRoomMapper, createMqttRoomDiscoveryDescriptor, mqttRoomProfile, type IMqttRoomSnapshot, type TMqttRoomRawData } from '../../ts/integrations/mqtt_room/index.js';

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

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

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

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

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

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

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

tap.test('documents MQTT Room Presence broker blocker and refuses generic HTTP fallback', async () => {
  const metadata = mqttRoomProfile.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_room');
  }) as typeof fetch;

  try {
    const snapshot = await new MqttRoomClient({ name: 'MQTT Room Live', host: '127.0.0.1', path: '/room_presence', transport: 'http' }).getSnapshot(true);
    expect(snapshot.online).toBeFalse();
    expect(snapshot.error!).toContain('state_topic/+');

    const runtime = await new MqttRoomIntegration().setup({ name: 'MQTT Room Runtime', host: '127.0.0.1', path: '/room_presence', transport: 'http' }, {});
    const status = await runtime.callService!({ domain: 'mqtt_room', service: 'status', target: {} });
    const runtimeSnapshot = status.data as IMqttRoomSnapshot;
    expect(runtimeSnapshot.online).toBeFalse();
    expect(runtimeSnapshot.error!).toContain('state_topic/+');
    await runtime.destroy();

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

  expect(metadata.runtime.controls).toBeFalse();
  expect(metadata.runtime.blocker).toContain('MQTT Room Presence live room updates require');
  expect(metadata.localApi.status).toContain('wildcard/QoS semantics');
  expect(metadata.localApi.explicitUnsupported.some((itemArg) => itemArg.includes('state_topic/+') && itemArg.includes('mqtt.async_subscribe'))).toBeTrue();
});

tap.test('exposes MQTT Room Presence runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MqttRoomIntegration();
  const alias = new HomeAssistantMqttRoomIntegration();
  expect(alias instanceof MqttRoomIntegration).toBeTrue();
  expect(alias.domain).toEqual("mqtt_room");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mqttRoomProfile.metadata.configFlow).toEqual(false);
  expect(mqttRoomProfile.metadata.requirements).toEqual([]);

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

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

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