module Memberships::Base

def email

def email
  user&.email || user_email.presence || invitation&.email
end

def first_name

def first_name
  user&.first_name || user_first_name
end

def first_name_last_initial

def first_name_last_initial
  [first_name, last_initial].select(&:present?).join(" ")
end

def full_name

def full_name
  user&.full_name || [first_name.presence, last_name.presence].join(" ").presence || email
end

def label_string

def label_string
  full_name
end

def last_admin?

def last_admin?
  return false unless admin?
  return false unless user.present?
  team.memberships.current.select(&:admin?) == [self]
end

def last_initial

def last_initial
  return nil unless last_name.present?
  "#{last_name[0]}."
end

def last_name

def last_name
  user&.last_name || user_last_name
end

def name

def name
  full_name
end

def nullify_user

def nullify_user
  if last_admin?
    raise RemovingLastTeamAdminException.new("You can't remove the last team admin.")
  end
  if (user_was = user)
    unless user_first_name.present?
      self.user_first_name = user.first_name
    end
    unless user_last_name.present?
      self.user_last_name = user.last_name
    end
    unless user_profile_photo_id.present?
      self.user_profile_photo_id = user.profile_photo_id
    end
    unless user_email.present?
      self.user_email = user.email
    end
    self.user = nil
    save
    user_was.invalidate_ability_cache
    user_was.update(
      current_team: user_was.teams.first,
      former_user: user_was.teams.empty?
    )
  end
  # we do this here just in case by some weird chance an active membership had an invitation attached.
  invitation&.destroy
end

def publish_changed_quantity

def publish_changed_quantity
  ActiveSupport::Notifications.instrument("memberships.quantity-changed", {team:})
end

def remove_user_profile_photo

def remove_user_profile_photo
  user_profile_photo.purge
end

def role_ids=(ids)

of a team.
associated with a membership, admins can never remove the last admin
we overload this method so that when setting the list of role ids
def role_ids=(ids)
  # if this membership was an admin, and the new list of role ids don't include admin.
  if admin? && !ids.include?(Role.admin.id)
    unless team.admins.count > 1
      raise RemovingLastTeamAdminException.new("You can't remove the last team admin.")
    end
  end
  super(ids)
end

def should_receive_notifications?

members shouldn't receive notifications unless they are either an active user or an outstanding invitation.
TODO utilize this.
def should_receive_notifications?
  invitation.present? || user.present?
end

def tombstone?

def tombstone?
  user.nil? && invitation.nil? && !platform_agent
end

def unclaimed?

def unclaimed?
  user.nil? && !invitation.nil?
end

def user_profile_photo_removal?

def user_profile_photo_removal?
  user_profile_photo_removal.present?
end