import { Links } from 'src/types/actionLinks';
import { EventActions } from 'src/types/events';
import { canPerformAction } from 'src/utils/actionsLinks';

import { CommentPermissions } from './types';

export type ComputeCommentPermissionsParams = {
  context: string;
  loggedUserId?: number;
  commentUserId: number;
  isGroupComment: boolean;

  // Group-specific parameters
  isGroupArchived?: boolean;
  userIsMember?: boolean;
  isGroupAdmin?: boolean;

  // Event-specific parameters
  links?: Links;

  // Standard context parameters
  canManageComments?: boolean;
  canReact?: boolean;
};

/**
 * Computes comment permissions based on context and user roles.
 */
export function computeCommentPermissions(
  params: ComputeCommentPermissionsParams,
): CommentPermissions {
  const {
    context,
    loggedUserId,
    commentUserId,
    isGroupComment,
    isGroupArchived = false,
    userIsMember = false,
    isGroupAdmin = false,
    canManageComments = false,
    canReact: canReactProp = false,
    links,
  } = params;

  const groupMemberContext = context === 'groups';
  const isEventContext = context === 'events';
  const isOwnComment = loggedUserId === commentUserId;

  // For events context with _links, use canPerformAction
  if (isEventContext && links) {
    const canDelete = canPerformAction(links, EventActions.DELETE);
    const canEdit = canPerformAction(links, EventActions.EDIT);
    const canReact = canReactProp;
    const canReply = true;
    return { canDelete, canReact, canEdit, canReply };
  }

  // Fallback to existing logic for other contexts
  const canDelete = groupMemberContext
    ? isOwnComment || isGroupAdmin
    : canManageComments;

  const canReact = groupMemberContext
    ? userIsMember && !isGroupArchived
    : canReactProp;

  const canEdit = isOwnComment && (!isGroupComment || !isGroupArchived);

  const canReply = !groupMemberContext || (userIsMember && !isGroupArchived);

  return {
    canDelete,
    canReact,
    canEdit,
    canReply,
  };
}
