class Competitions::JoinTeamService < ApplicationService
  Error = Class.new(StandardError)

  attr_reader :competition, :user, :params

  def initialize(competition, user, params)
    @competition = competition
    @user        = user
    @params      = params
  end

  def call
    invite_code = params[:invite_code].to_s.strip
    raise Error, '战队邀请码不能为空' if invite_code.blank?

    is_teacher = user.is_teacher?
    raise Error, '本竞赛的参赛者限定为：学生' if is_teacher && competition.teacher_enroll_forbidden?
    raise Error, '本竞赛的参赛者限定为：教师' if !is_teacher && competition.member_enroll_forbidden?

    team = competition.competition_teams.find_by(invite_code: invite_code)
    raise Error, '战队邀请码无效' if team.blank?
    raise Error, '您已加入该战队' if team.team_members.exists?(user_id: user.id)

    enrolled = competition.team_members.exists?(user_id: user.id)
    if enrolled && (is_teacher && competition.teacher_multiple_limited?) || (!is_teacher && competition.member_multiple_limited?)
      raise Error, '您已加入其它战队'
    end

    raise Error, '该战队教师人数已满' if is_teacher && team.teachers.count == competition.teacher_staff.maximum
    raise Error, '该战队队员人数已满' if !is_teacher && team.members.count == competition.member_staff.maximum

    role = is_teacher ? 3 : 2
    team.team_members.create!(competition_id: competition.id, user_id: user, role: role, is_teacher: is_teacher)
  end
end