class Competitions::CompetitionTeamsController < Competitions::BaseController
  def index
    admin_or_business? ? all_competition_teams : user_competition_teams
  end

  def create
    if current_competition.personal? # 个人赛报名
      Competitions::CreatePersonalTeamService.call(current_competition, current_user)
    else
      team = current_competition.competition_teams.new(user: current_user)
      Competitions::SaveTeamService.call(team, save_params)
    end
    render_ok

  rescue Competitions::CreatePersonalTeamService::Error => ex
    render_error(ex.message)
  end

  def update
    team = current_competition.competition_teams.where(user: current_user).find(params[:id])
    Competitions::SaveTeamService.call(team, save_params)
    render_ok
  end

  def join
    Competitions::JoinTeamService.call(current_competition, current_user, params)
    render_ok
  rescue Competitions::JoinTeamService::Error => ex
    render_error(ex.message)
  end

  def leave
    team = current_competition.competition_teams.find(params[:id])
    member = team.team_members.find_by(user_id: current_user.id)
    return render_error('您不是该战队的成员') if member.blank?

    if member.user_id == team.user_id
      team.destroy! # 队长退出，战队解散
    else
      member.destroy!
    end

    render_ok
  end

  private

  def all_competition_teams
    teams = current_competition.competition_teams

    keyword = params[:keyword].to_s.strip
    if keyword.present?
      teams = teams.joins(users: { user_extension: :school }).where('schools.name LIKE ?', "%#{keyword}%")
    end

    @count = teams.count
    @teams = paginate(teams.includes(:user, users: { user_extension: :school }))
  end

  def user_competition_teams
    teams  = current_competition.competition_teams
    teams  = teams.joins(:team_members).where(team_members: { user_id: current_user.id })
    @teams = teams.includes(:user, users: { user_extension: :school }).to_a
    @count = @teams.size
  end

  def save_params
    params.permit(:name, teacher_ids: [], member_ids: [])
  end
end
