class Google::Sheets::Covid::EmployeeScreeningService < Google::Sheets::ApplicationService
  include DateRangeHelper

  def initialize(school, user, date_range)
    @school = school
    @date_range = datetime_range(date_range)
    @label = 'Covid Screenings'
    super(user)
  end

  private
    def body
      data = []
      data << headers
      screenings.each { |s| data << s }
      data
    end

    def headers
      attributes = [
        'Date/Time',
        'Last Name',
        'First Name'
      ]
      attributes + questions.map(&:title)
    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

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