class Admin::Legacy::Student::ActivityStudentsController < Admin::Legacy::Student::Controller
  def index
    data = if params[:enrolled]&.to_bool
      students.where(student_id: activity_students.keys)
    else
      students.where.not(student_id: activity_students.keys)
    end

    data = data.distinct
      .pluck(:student_id, 'Students.FirstName', 'Students.LastName', :grade_id)
      .map do |id, first, last, grade|
        first, last = encode_strings_to_utf8([first, last])
        {
          id: id,
          full_name: "#{last}, #{first}",
          grade_label: grade_levels[activity_students[id]&.dig(:grade)] || grade_levels[grade],
          activity_id: activity_students[id]&.dig(:id)
        }
      end

    render_success :ok, json: data
  end

  def batch_create
    data = params[:ids].map do |id|
      activity.activity_students.build(student_id: id, school_year: year, school: current_school)
    end

    if transactional_save(data)
      render_success :created
    else
      render_error :unprocessable_entity
    end
  end

  def batch_delete
    data = current_school.student_activity_students.where(id: params[:ids])

    if transactional_destroy(data)
      render_success :ok
    else
      render_error :unprocessable_entity
    end
  end

  private
    def activity
      @activity ||= current_school.student_activities.find_by(id: params[:activity_id])
    end

    def students
      year.school_year_students
        .includes(:student)
        .by_grades(params[:grade_ids])
        .distinct(:student_id)
    end

    def activity_students
      @activity_students ||= year.student_activity_students
        .by_activity_ids(params[:activity_id])
        .pluck(:student_id, :grade, :id)
        .map { |s, g, i| [s, { grade: g, id: i }] }
        .to_h
    end

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