import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantMqttStatestreamIntegration, MqttStatestreamClient, MqttStatestreamConfigFlow, MqttStatestreamIntegration, MqttStatestreamMapper, createMqttStatestreamDiscoveryDescriptor, mqttStatestreamProfile, type IMqttStatestreamSnapshot, type TMqttStatestreamRawData } from '../../ts/integrations/mqtt_statestream/index.js';

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

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

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

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

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

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

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

tap.test('exposes MQTT Statestream runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new MqttStatestreamIntegration();
  const alias = new HomeAssistantMqttStatestreamIntegration();
  expect(alias instanceof MqttStatestreamIntegration).toBeTrue();
  expect(alias.domain).toEqual("mqtt_statestream");
  expect(integration.status).toEqual("read-only-runtime");
  expect(mqttStatestreamProfile.metadata.configFlow).toEqual(false);
  expect(mqttStatestreamProfile.metadata.requirements).toEqual([]);
  expect(String((mqttStatestreamProfile.metadata.localApi as Record<string, unknown>).status)).toContain('MQTT broker semantics');

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

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

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