import { ROLE, User } from 'redux/User/types'

export const userHasRole = (
  user: User | null | undefined | (User | null | undefined)[],
  role: string
): boolean => {
  const userObjects = Array.isArray(user) ? user : [user]

  return userObjects.some(user =>
    Boolean(user?.roles?.find(userRole => userRole.name === role))
  )
}

export function isAdminLike(
  user: User | null | undefined | (User | null | undefined)[]
) {
  return (
    userHasRole(user, ROLE.Admin) ||
    userHasRole(user, ROLE.Moderator) ||
    userHasRole(user, ROLE.External)
  )
}

/*
checks whether the user accessing the profile (i.e user.id/ user.authenticatedUserId) is same as the one who created the profile
  user.id - profile user
  authenticatedUserId - the user who is logged in
*/
export function hasOwnership(user?: User | null) {
  return (
    user &&
    (user.id === user.talentProfile?.user?.createdById ||
      user?.authenticatedUserId === user.talentProfile?.user?.createdById)
  )
}
