class Competitions::CompetitionsController < Competitions::BaseController
  skip_before_action :require_login

  def index
    # 已上架 或者 即将上架
    competitions = Competition.where(status: true).or(Competition.where.not(published_at: nil))

    competitions =
      case params[:category]
      when 'nearly_published' then competitions.where(status: false)
      when 'progressing' then competitions.where('end_time > NOW()')
      when 'ended'       then competitions.where('end_time < NOW()')
      else competitions
      end

    @count = competitions.count

    competitions = competitions.order(published_at: :desc, online_time: :desc)
    @competitions = paginate(competitions.includes(current_stage_section: :competition_stage))

    ids = @competitions.map(&:id)
    @member_count_map = TeamMember.where(competition_id: ids).group(:competition_id).count
    @stage_count_map  = CompetitionStage.where(competition_id: ids).group(:competition_id).count
  end

  def show
    unless current_competition.published? || admin_or_business?
      render_forbidden
      return
    end
  end

  private

  def current_competition
    @_current_competition ||= Competition.find_by!(identifier: params[:id])
  end
end