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

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

type Event = {
  ts: string;
  channel: string;
  type: string;
};

const conversationInfoDBRequiredFieldsSchema = z
  .object({
    id: requiredString,
    other_user: userDBRequiredFieldsSchema.optional(),
    latest: z
      .object({
        client_msg_id: requiredString,
        ts: requiredString,
        user: requiredUserId,
        username: requiredString,
        attachments: z.array(assetDBRequiredFieldsSchema).optional(),
      })
      .passthrough()
      .nullable()
      .optional(),
  })
  .passthrough();

const logConversationInfoDBValidation = ({
  conversation,
  event,
  issues,
}: {
  conversation: Conversation;
  event: Event;
  issues: string[];
}) => {
  sentryLogs.error({
    message:
      '[Events Validation] Conversation info response has invalid DB-required fields',
    module: 'CHATS',
    component: 'socketEvents',
    data: {
      endpoint: 'marty/conversations.info',
      eventName: event.type,
      eventTs: event.ts,
      eventChannel: event.channel,
      conversationId: conversation.id,
      latestClientMsgId: conversation.latest?.client_msg_id,
      latestTs: conversation.latest?.ts,
      latestUser: conversation.latest?.user,
      otherUserId: conversation.other_user?.id,
      otherUserFirstName: conversation.other_user?.first_name,
      otherUserLastName: conversation.other_user?.last_name,
      issues,
    },
  });
};

export const logConversationInfoDBValidationIssues = (
  conversation: Conversation,
  event: Event,
) => {
  const validation = getValidationResult(
    conversationInfoDBRequiredFieldsSchema,
    conversation,
  );
  if (!validation.success) {
    logConversationInfoDBValidation({
      conversation,
      event,
      issues: validation.issues,
    });
  }
};
