class Pdf::Nursing::MissingVaccinationService < Pdf::NewApplicationService
  def initialize(school, students)
    @students = students.decorate
    @school = school
  end

  private
    def header
      content = ActionController::Base.new.render_to_string(
        partial: 'pdf/headers/school_info.html.haml',
        locals: {
          school: @school,
          side_content_partial: 'pdf/nursing/missing_vaccination_header.html.haml',
          side_content: { date: Time.zone.now.to_date }
        }
      )
      { content: content, spacing: 25 }
    end

    def body
      ActionController::Base.new.render_to_string(
        partial: 'pdf/nursing/missing_vaccination.html.haml',
        locals: set_local_variables
      )
    end

    def set_local_variables
      {
        students: filtered_students,
        grade_labels: @school.grades_hash
      }
    end

    def filtered_students
      @students.map do |student|
        missing_vaccines = vaccines.select do |vaccine|
          record = student.nursing_vaccine_records.find { |r| r.vaccine_id == vaccine.vaccine_id }
          next if record && (record.vaccine_date || !record.not_exempt?)

          student.grade >= vaccine.grade
        end

        [student, missing_vaccines] if missing_vaccines.present?
      end.compact.to_h
    end

    def vaccines
      @vaccines ||= @school.nursing_vaccine_configs
        .includes(:vaccine)
        .by_required
        .ordered
        .decorate
    end
end
