class Admin::Legacy::Student::Students::SchoolYearsController < ApplicationController
  def index
    render_success :ok, json: school_year_students.map { |s| school_year_props(s) }
  end

  def show
    render_success :ok, json: school_year_props(school_year_student)
  end

  def update
    if school_year_student.update(school_year_student_params)
      render_success :ok, json: school_year_props(school_year_student)
    else
      render_error :unprocessable_entity, errors: school_year_student
    end
  end

  private
    def school_year_students
      student.school_year_students.includes(:school_year)
    end

    def school_year_student
      @school_year_student ||= school_year_students.find_by(id: params[:id])
    end

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

    def ed_fi_choice
      school_year_student.find_or_build_ed_fi_choice
    end

    def school_year_student_params
      params.permit(
        :grade_id,
        :entry_date,
        :exit_date,
        :exit_type,
        :primary_school,
        ed_fi_choice_attributes: [:id, :value]
      )
    end

    def school_year_props(school_year_student)
      {}.tap do |props|
        props[:id] = school_year_student.id
        props[:school_year_id] = school_year_student.school_year_id
        props[:school_year_name] = school_year_student.decorate.school_year_name
        props[:academic_year] = school_year_student.decorate.school_year_academic_year
        props[:grade_id] = school_year_student.grade_id
        props[:grade_name] = school_year_student.decorate.grade_name
        props[:entry_date] = school_year_student.entry_date
        props[:exit_date] = school_year_student.exit_date
        props[:exit_type] = school_year_student.exit_type? ? school_year_student.exit_type : nil
        props[:primary_school] = school_year_student.primary_school?
        return props unless action_name.to_sym == :show && current_school.ed_fi_system_indiana?

        props[:ed_fi_choice_attributes] = { id: ed_fi_choice.id, value: ed_fi_choice.value }
      end
    end
end
