class Employee::Legacy::Classrooms::Assignments::Grades::StudentsController < Employee::Controller
  include Employee::ClassroomScoped

  def index
    render_success :ok, json: students.map { |s| student_grade_props(s) }
  end

  def update
    grade = assignment.class_grades.find_or_initialize_by(student: student, classroom: classroom)
    grade.assign_attributes(grade_params)

    if grade.save
      render_success :ok, object: 'class grade'
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  def batch_update
    grades = []
    students.where(id: params[:students].pluck(:student_id)).each do |student|
      grade = assignment.class_grades.find_or_initialize_by(student: student, classroom: classroom)
      param = params[:students].find { |i| i[:student_id] == student.id }
      grade.assign_attributes(grade_params(param))
      grades << grade
    end

    if transactional_save(grades)
      render_success :ok, message: 'Class Grades Updated'
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  private
    def students
      classroom.students
    end

    def student
      @student ||= students.find_by(id: params[:id])
    end

    def assignment
      @assignment ||= classroom.class_assignments.find_by(id: params[:assignment_id])
    end

    def student_grades
      @student_grades ||= assignment.class_grades.index_by(&:student_id)
    end

    def author
      @author ||= current_school.employees.find_by(id: params[:author_id])
    end

    def grade_params(param)
      param.permit(:number, :comments, :status).merge(author: current_user)
    end

    def student_grade_props(student)
      grade = student_grades[student.id]
      {}.tap do |props|
        props[:id] = student.id
        props[:full_name] = student.full_name
        props[:first_name] = student.first_name
        props[:last_name] = student.last_name
        props[:number] = grade&.number
        props[:comments] = grade&.comments
        props[:status] = grade&.status
        props[:author] = grade&.author&.full_name
      end
    end
end
