class Admins::ApproveCompetitionPrizeUserService < ApplicationService
  attr_reader :competition, :prize_user, :approver

  def initialize(prize_user, approver)
    @competition = prize_user.competition
    @prize_user  = prize_user
    @approver    = approver
  end

  def call
    raise Error, '请勿重复审批' if prize_user.approved?
    raise Error, '该用户未认证完成' unless prize_user.user_certified?

    prize = prize_user.competition_prize

    ActiveRecord::Base.transaction do
      prize_user.approve
      prize_user.approver = approver
      prize_user.approved_at = Time.now
      prize_user.save!

      # 生成个人证书
      # 是老师并且教师证书模板存在 或者是学生而且个人证书模板存在
      if (prize_user.user.is_teacher? && prize.teacher_certificate_exists?) ||
          (!prize_user.user.is_teacher? && prize.member_certificate_exists?)
        GenerateCompetitionPersonalCertificateJob.perform_later(prize_user.id)
      end

      # 生成团队证书
      if !competition.personal? && prize_user.competition_team.all_prize_approved? && prize.team_certificate_exists?
        GenerateCompetitionTeamCertificateJob.perform_later(prize_user.competition_team.id)
      end
    end
  end
end