# frozen_string_literal: true
class ReviewerVote < ApplicationRecord
  belongs_to :candidate
  belongs_to :user

  validates :user_id, uniqueness: { scope: :candidate_id }

  after_save :notify_manager

  enum vote: {
    undecided: 0,
    yea: 1,
    nay: 2
  }

  enum veto: {
    approved: 1,
    declined: 2
  }

  private

    def notify_manager
      ReviewerMailer.notify_manager(candidate_id).deliver_now if all_reviewers_voted?
    end

    def all_reviewers_voted? # rubocop:disable Metrics/MethodLength
      sql = " select distinct rev.candidate_id
                  , full_votes.voters, full_votes.vote_count
                  , c.test_hash
              from reviewer_votes rev
                inner join users u on u.id = rev.user_id
                  inner join candidates c on c.id = rev.candidate_id
                  left join (
                  select candidate_id
                      from reviewer_votes
                      where veto > 0 or veto is null
                  ) as vetos on vetos.candidate_id = rev.candidate_id
                  left join (
                  select candidate_id
                    , count(vote) voters
                          , sum(case when vote != 0 then 1 else 0 end) vote_count
                      from reviewer_votes
                    left join users on users.id = reviewer_votes.user_id
                  where users.role != 'manager'
                      group by candidate_id
                  ) as full_votes on full_votes.candidate_id = rev.candidate_id
              where vetos.candidate_id is null
                and full_votes.voters = full_votes.vote_count
                and rev.candidate_id = #{candidate_id};"
      result = ActiveRecord::Base.connection.exec_query(sql)
      result.count == 1
    end # rubocop:enable Metrics/MethodLength
end
