import { SimpleLocalClient } from '../../core/index.js';
import { MqttEventstreamMapper } from './mqtt_eventstream.mapper.js';
import type { IMqttEventstreamConfig, IMqttEventstreamSnapshot } from './mqtt_eventstream.types.js';
import { mqttEventstreamLiveUnsupportedReason, mqttEventstreamProfile } from './mqtt_eventstream.types.js';

export class MqttEventstreamClient extends SimpleLocalClient<IMqttEventstreamConfig> {
  constructor(private readonly configArg: IMqttEventstreamConfig) {
    super(mqttEventstreamProfile, safeSnapshotConfig(configArg));
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IMqttEventstreamSnapshot> {
    if (!hasSafeSnapshotSource(this.configArg)) {
      return MqttEventstreamMapper.toSnapshot({ config: this.configArg, online: false, source: 'runtime', error: mqttEventstreamLiveUnsupportedReason }) as IMqttEventstreamSnapshot;
    }

    return await super.getSnapshot(forceRefreshArg) as IMqttEventstreamSnapshot;
  }
}

const hasSafeSnapshotSource = (configArg: IMqttEventstreamConfig): boolean => Boolean(
  configArg.client
  || configArg.snapshotProvider
  || configArg.snapshot
  || configArg.rawData !== undefined
  || configArg.rawText !== undefined
  || configArg.entities?.length,
);

const safeSnapshotConfig = (configArg: IMqttEventstreamConfig): IMqttEventstreamConfig => ({
  ...configArg,
  host: undefined,
  port: undefined,
  path: undefined,
  transport: configArg.transport === 'snapshot' ? 'snapshot' : undefined,
  tcpCommand: undefined,
  url: undefined,
});
