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

import {getValidationResult, numericString, requiredInt} from './shared';

const membershipDBRequiredFieldsSchema = z
  .object({
    version: requiredInt,
    is_admin: z.boolean().optional(),
    user: z
      .object({
        id: z.union([numericString, requiredInt]),
      })
      .passthrough(),
  })
  .passthrough();

const logMembershipDBValidation = ({
  membership,
  channelId,
  eventType,
  issues,
}: {
  membership: MembershipFromServer;
  channelId: string;
  eventType: string;
  issues: string[];
}) => {
  sentryLogs.error({
    message:
      '[Events Validation] Membership data has invalid DB-required fields',
    module: 'CHATS',
    component: 'socketEvents',
    data: {
      eventType,
      channelId,
      membershipUserId: membership.user?.id,
      membershipVersion: membership.version,
      membershipIsAdmin: membership.is_admin,
      issues,
    },
  });
};

export const logMembershipDBValidationIssues = (
  membership: MembershipFromServer,
  channelId: string,
  eventType: string,
) => {
  const validation = getValidationResult(
    membershipDBRequiredFieldsSchema,
    membership,
  );
  if (!validation.success) {
    logMembershipDBValidation({
      membership,
      channelId,
      eventType,
      issues: validation.issues,
    });
  }
};
