class Admin::Legacy::Service::StudentsController < Admin::Legacy::Service::Controller
  def index
    data = students.map do |id, first_name, last_name, grade|
      first_name, last_name = encode_strings_to_utf8([first_name, last_name])
      props = props(id)
      props[:id] = id
      props[:full_name] = "#{last_name}, #{first_name}"
      props[:grade_label] = grade_levels[grade]
      props[:grade] = grade
      props
    end
    render_success :ok, json: data
  end

  def statistics
    data = current_school.students.find_by(id: params[:id]).service_logs
      .by_school_year(current_school_year)
      .group(:status)
      .sum(:hours)
    render_success :ok, json: {
      approved: data['approved'] || 0,
      pending: data['pending'] || 0,
      denied: data['denied'] || 0
    }
  end

  def export
    send_data ::Service::StudentsCsvService.call(current_school)
  end

  private
    def students
      current_school.students
        .by_grade(params[:grade])
        .by_classroom(params[:classroom_ids])
        .current_status(current_school, params[:status]&.to_sym)
        .pluck(:id, :first_name, :last_name, :grade)
    end

    def requirement
      @requirement ||= current_school.find_or_build_service_requirement.student_hours
    end

    def approved_hours
      @approved_hours ||= current_school.service_student_logs
        .by_school_year(current_school_year)
        .approved
        .group(:student_id)
        .sum(:hours)
    end

    def pending_hours
      @pending_hours ||= current_school.service_student_logs
        .by_school_year(current_school_year)
        .pending
        .group(:student_id)
        .sum(:hours)
    end

    def props(id)
      percentage = (approved_hours[id] || 0) / requirement * 100 if requirement.positive?

      {
        approved: approved_hours[id] || 0,
        pending: pending_hours[id] || 0,
        percentage: percentage
      }
    end
end
