import {EventsSocketsType} from '@config/constants';
import {ChatEvent, ChatEventType} from '@modules/chats/interfaces';
import {CHATS_EVENTS_MAPPER, EventSocketName} from '@modules/chats/constants';
import {sentryLogs} from '@shared/utils';

const getEventName = (event: ChatEvent): EventsSocketsType => {
  const key: EventSocketName =
    event.type === ChatEventType.message
      ? ChatEventType.message
      : (`${event.type}${
          event.subtype ? `:${event.subtype}` : ''
        }` as EventSocketName);

  return CHATS_EVENTS_MAPPER[key];
};

export const mapEventsToSocket = (events: ChatEvent[]) => {
  const mappedEvents: {
    name: EventsSocketsType;
    data: Record<string, unknown>;
  }[] = [];
  for (const event of events) {
    const eventName = getEventName(event);
    if (eventName) {
      mappedEvents.push({
        name: eventName,
        data: {...event, _source: 'events'} as unknown as Record<
          string,
          unknown
        >,
      });
    } else {
      sentryLogs.warn({
        message: 'Unknown event type — skipped during sync',
        module: 'CHATS',
        component: 'mapEventsToSocket',
        data: {
          type: event.type,
          subtype: event.subtype,
          ts: event.ts,
        },
      });
    }
  }

  return mappedEvents;
};
