class Competitions::CreatePersonalTeamService < ApplicationService

  attr_reader :competition, :user

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

  def call
    raise Error, '个人赛才能报名' unless competition.personal?

    raise Error, '本竞赛只面向部分学校/单位开放，你暂时没有参赛资格' unless competition.open?(user)

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

    enrolled = competition.competition_teams.exists?(user_id: user.id)
    multiple_limited = (is_teacher && competition.teacher_multiple_limited?) || (!is_teacher && competition.member_multiple_limited?)
    raise Error, '您已报名该竞赛' if enrolled && multiple_limited

    ActiveRecord::Base.transaction do
      team = competition.competition_teams.create!(name: user.real_name, user_id: user.id)
      team.team_members.create!(competition_id: competition.id, user_id: user.id, role: 1, is_teacher: is_teacher)
    end
  end
end