class Admin::Legacy::Student::Students::Indiana::EnrollmentsController <
  Admin::Legacy::Student::Controller
  def index
    if student_id
      render_success :ok, json: enrollment_service.index_by_student(student_id)
    else
      render_success :ok, json: []
    end
  end

  def show
    render_success :ok, json: enrollment_service.find_record(params[:id])
  end

  def destroy
    if params[:id] && transaction_delete
      render_success :ok, json: { success: true }
    else
      render_error :unprocessable_entity, json: { success: false }
    end
  end

  private
    def student
      current_school.students.find_by(id: params[:student_id])
    end

    def school_year_student
      current_school.school_year_students.find_by(edfi_id: params[:id])
    end

    def student_id
      @student_id ||= student&.state_number&.number
    end

    def transaction_delete
      if school_year_student.blank?
        enrollment_service(params[:id]).delete
      else
        school_year_student.transaction do
          school_year_student&.destroy
          enrollment_service(params[:id]).delete
        end
      end
    end

    def enrollment_service(edfi_id=nil)
      EdFi::Indiana::Sandbox::StudentSchoolAssociationService.new(
        current_school_year.id,
        student: student,
        id: edfi_id
      )
    end
end
