class Admin::Legacy::Student::ActivitiesController < Admin::Legacy::Student::Controller
  def index
    render_success :ok, json: activities.map { |activity| props(activity) }
  end

  def show
    render_success :ok, json: props(activity)
  end

  def create
    activity = activities.build(activity_params)
    if activity.save
      render_success :created, json: props(activity)
    else
      render_error :unprocessable_entity, errors: activity
    end
  end

  def update
    if activity.update(activity_params)
      render_success :ok, json: props(activity)
    else
      render_error :unprocessable_entity, errors: activity
    end
  end

  def destroy
    if activity.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: activity
    end
  end

  private
    def activities
      current_school.student_activities
    end

    def activity
      @activity ||= activities.find_by(id: params[:id])
    end

    def activity_params
      params.permit(:name, :description)
    end

    def student_count
      @student_count ||= year.student_activity_students
        .by_activity_ids(params[:id])
        .group(:activity_id)
        .size
    end

    def year
      @year ||= current_school.school_years.find_by(id: params[:year_id]) || current_school_year
    end

    def props(activity)
      {
        id: activity.id,
        name: activity.name,
        description: activity.description,
        year_id: year.id,
        student_count: student_count[activity.id] || 0
      }
    end
end
