class Csv::Covid::EmployeeScreeningService < Csv::ApplicationService
  include DateRangeHelper

  def initialize(school, date_range)
    @school = school
    @date_range = datetime_range(date_range)
  end

  def call
    CSV.generate do |csv|
      csv << headers
      screenings.each { |s| csv << s }
    end
  end

  private
    def headers
      attributes = [
        'Date/Time',
        'Last Name',
        'First Name'
      ]
      attributes + questions.map(&:title)
    end

    def questions
      @questions ||= @school.covid_form_questions
        .by_employee_field(true)
        .order('covid_form_sections.sequence ASC', :sequence)
    end

    def screenings
      @school.covid_employee_screenings
        .preload(:employee, answers: :options)
        .by_date_range(@date_range)
        .map { |s| screening_props(s) }
    end

    def screening_props(screening)
      attributes = [
        screening.decorate.recorded_at,
        screening.employee.last_name,
        screening.employee.first_name
      ]

      attributes + questions.map do |question|
        answers = screening.answers.find { |a| a.question_id == question.id }
        if question.has_options?
          answers&.options&.map(&:value)&.join(' ')
        else
          answers&.value
        end
      end
    end
end
