class ProjectMembership < ApplicationRecord
  belongs_to :project
  belongs_to :user

  validates :user_id, uniqueness: { scope: :project_id, message: "already belongs to this Project" }
  validate :account_manager_is_prohibited

  scope :with_account_auth, -> (account) { joins(user: :account_auths).where(account_auths: { account_id: account }) }
  scope :order_by_user_role_and_user_email, -> (account) { with_account_auth(account).order("account_auths.role DESC, users.email") }

  attr_accessor :user_email

  def new_user?
    @user_is_new
  end

  def save_and_update_account_membership
    ApplicationRecord.transaction do
      if User.exists?(email: user_email)
        @user_is_new = false
        self.user = User.find_by(email: user_email)
      else
        @user_is_new = true
        self.user = Oath::Services::SignUp.new(email: user_email, password: SecureRandom.hex).perform
      end

      account_auth = user.account_auths.find_or_initialize_by(account: project.account)

      if !(user.save && account_auth.save && save)
        raise ActiveRecord::Rollback
        return false
      end

      return true
    end
  end

  private

  def account_manager_is_prohibited
    return if project.nil?

    if user.account_manager?(project.account)
      errors.add(:user, "is already an account manager")
    end
  end
end
