class Csv::AppleManager::StudentService < Csv::ApplicationService
  def initialize(school)
    @school = school
  end

  def call
    CSV.generate do |csv|
      csv << headers
      students.each do |student|
        next if missing_data?(student)

        csv << content(student)
      end
    end
  end

  private
    def config
      @school.find_or_build_apple_manager_config
    end

    def students
      @school.students
        .preload(:user, :state_number, :school_number)
        .joins(:user)
        .join_school_year_student(@school.current_year.id, :current)
    end

    def missing_data?(student)
      [:first_name, :last_name, :location_id?].any? { |p| student.send(p).blank? }
    end

    def headers
      [
        'person_id',
        'person_number',
        'first_name',
        'middle_name',
        'last_name',
        'grade_level',
        'email_address',
        'sis_username',
        'password_policy',
        'location_id'
      ]
    end

    def content(student)
      [
        student.user_id,
        student.decorate.send(config.student_identifier),
        student.first_name,
        student.middle_name,
        student.last_name,
        student.grade,
        student.email,
        student.user.username,
        nil,
        student.location_id
      ]
    end
end
