import {z} from 'zod';
import {ReactionEvent} from '@modules/chats/interfaces';
import {sentryLogs} from '@shared/utils';

import {getValidationResult, requiredString, requiredUserId} from './shared';

const reactionEventDBRequiredFieldsSchema = z
  .object({
    client_msg_id: requiredString,
    channel: requiredString,
    hu_data: z
      .object({
        message_ts: requiredString,
      })
      .passthrough(),
    reactions: z.array(
      z
        .object({
          name: requiredString,
          users: z.array(requiredUserId),
        })
        .passthrough(),
    ),
  })
  .passthrough();

const logReactionEventDBValidation = ({
  event,
  issues,
}: {
  event: ReactionEvent;
  issues: string[];
}) => {
  sentryLogs.error({
    message:
      '[Events Validation] Reaction event has invalid DB-required fields',
    module: 'CHATS',
    component: 'socketEvents',
    data: {
      eventTs: event.ts,
      channel: event.channel,
      clientMsgId: event.client_msg_id,
      messageTs: event.hu_data?.message_ts,
      reactionsCount: Array.isArray(event.reactions)
        ? event.reactions.length
        : undefined,
      issues,
    },
  });
};

export const logReactionEventDBValidationIssues = (event: ReactionEvent) => {
  const validation = getValidationResult(
    reactionEventDBRequiredFieldsSchema,
    event,
  );
  if (!validation.success) {
    logReactionEventDBValidation({event, issues: validation.issues});
  }
};
