import type { EmsRecordAlarmDataVO } from '@/api/ems/types';

export const EMS_REALTIME_ALARM_EVENT = 'ems:alarm:realtime';
export const EMS_REALTIME_ALARM_PAYLOAD_TYPE = 'ems_alarm_realtime';

export interface EmsRealtimeAlarmEnvelope {
  eventType: typeof EMS_REALTIME_ALARM_PAYLOAD_TYPE;
  channel?: 'SSE' | 'WEBSOCKET' | 'UNKNOWN';
  source?: string;
  generatedAt?: string;
  alarms: EmsRecordAlarmDataVO[];
}

interface LegacyRealtimeAlarmEnvelope {
  eventType?: string;
  source?: string;
  eventTime?: string;
  payload?: {
    records?: EmsRecordAlarmDataVO[];
  };
}

export interface ParsedAlarmMessage {
  envelope: EmsRealtimeAlarmEnvelope | null;
  displayMessage: string;
}

export const useAlarmRealtimeBus = () => useEventBus<EmsRealtimeAlarmEnvelope>(EMS_REALTIME_ALARM_EVENT);

const isRealtimeAlarmEnvelope = (value: unknown): value is EmsRealtimeAlarmEnvelope => {
  if (!value || typeof value !== 'object') {
    return false;
  }
  const envelope = value as EmsRealtimeAlarmEnvelope;
  return envelope.eventType === EMS_REALTIME_ALARM_PAYLOAD_TYPE && Array.isArray(envelope.alarms);
};

const normalizeLegacyEnvelope = (value: unknown): EmsRealtimeAlarmEnvelope | null => {
  if (!value || typeof value !== 'object') {
    return null;
  }
  const legacyEnvelope = value as LegacyRealtimeAlarmEnvelope;
  const records = legacyEnvelope.payload?.records;
  if (legacyEnvelope.eventType !== 'EMS_REALTIME_ALARM_BATCH' || !Array.isArray(records)) {
    return null;
  }
  return {
    eventType: EMS_REALTIME_ALARM_PAYLOAD_TYPE,
    source: legacyEnvelope.source,
    generatedAt: legacyEnvelope.eventTime,
    alarms: records
  };
};

export const parseAlarmRealtimeMessage = (rawMessage: unknown): ParsedAlarmMessage => {
  const fallbackMessage = typeof rawMessage === 'string' ? rawMessage : JSON.stringify(rawMessage ?? '');
  if (typeof rawMessage !== 'string') {
    return {
      envelope: null,
      displayMessage: fallbackMessage
    };
  }
  try {
    const parsed = JSON.parse(rawMessage);
    const envelope = isRealtimeAlarmEnvelope(parsed) ? parsed : normalizeLegacyEnvelope(parsed);
    if (!envelope) {
      return {
        envelope: null,
        displayMessage: fallbackMessage
      };
    }
    const firstAlarm = envelope.alarms[0];
    const alarmCount = envelope.alarms.length;
    const displayMessage =
      alarmCount > 1
        ? `收到 ${alarmCount} 条实时告警，已进入待处置队列`
        : `收到实时告警：${firstAlarm?.alarmTitle || firstAlarm?.monitorName || firstAlarm?.monitorId || '未命名告警'}`;
    return {
      envelope,
      displayMessage
    };
  } catch {
    return {
      envelope: null,
      displayMessage: fallbackMessage
    };
  }
};
