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

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

const assetChangedEventDBRequiredFieldsSchema = z
  .object({
    client_msg_id: requiredString,
    channel: requiredString,
    attachments: z.array(assetDBRequiredFieldsSchema),
  })
  .passthrough();

const logAssetChangedEventDBValidation = ({
  event,
  issues,
}: {
  event: AssetChangedEvent;
  issues: string[];
}) => {
  sentryLogs.error({
    message:
      '[Events Validation] AssetChanged event has invalid DB-required fields',
    module: 'CHATS',
    component: 'socketEvents',
    data: {
      eventTs: event.ts,
      channel: event.channel,
      clientMsgId: event.client_msg_id,
      attachmentsCount: Array.isArray(event.attachments)
        ? event.attachments.length
        : undefined,
      issues,
    },
  });
};

export const logAssetChangedEventDBValidationIssues = (
  event: AssetChangedEvent,
) => {
  const validation = getValidationResult(
    assetChangedEventDBRequiredFieldsSchema,
    event,
  );
  if (!validation.success) {
    logAssetChangedEventDBValidation({event, issues: validation.issues});
  }
};
