class Competitions::CertificatesController < Competitions::BaseController
  def personal
    prize_user =
      if current_user.admin_or_business?
        CompetitionPrizeUser.find(params[:id])
      else
        CompetitionPrizeUser.find_by!(user: current_user, id: params[:id])
      end
    return render_not_found unless prize_user.certificate_exist?

    team = prize_user.competition_team
    prize = prize_user.competition_prize
    filename = "#{current_competition.name}-#{prize.name}-#{team.name}-#{prize_user.user.real_name}.pdf"

    send_file prize_user.certificate_path, filename: filename
  end

  def team
    team = CompetitionTeam.find(params[:id])
    return render_forbidden unless current_user.admin_or_business? || team.team_members.exists?(user_id: current_user.id)
    return render_not_found unless team.certificate_exists?

    prize = team.competition_prize_users.first.competition_prize
    filename = "#{current_competition.name}-#{prize.name}-#{team.name}.pdf"

    send_file team.certificate_path, filename: filename
  end
end