class Family::Covid::ScreeningsController < Family::Controller
  def new
    render_success :ok, json: Covid::ScreeningForm.call(current_school)
  end

  def create
    form = student.covid_screenings.build(date: params[:date])
    questions.each do |question|
      answer = params[:answers].find { |a| a[:field_id] == question.id }[:value]
      if question.has_options?
        form_answer = form.answers.build(question: question)
        form_answer.options = options_by_question[question.id]
      else
        form.answers.build(question: question, value: answer)
      end
    end

    if form.save
      render_success :ok
    else
      render_error :unprocessable_entity, errors: form
    end
  end

  private
    def questions
      current_school.covid_form_questions
        .where(id: params[:answers].pluck(:field_id))
        .by_employee_field(false)
    end

    def options_by_question
      @options_by_question ||= current_school.covid_form_options
        .where(id: params[:answers].pluck(:value).flatten)
        .group_by(&:field_id)
    end
end
