class Employee::Covid::ScreeningsController < Employee::Controller
  def show
    render_success :ok, json: { completed: screening.present? }
  end

  def new
    render_success :ok, json: Covid::ScreeningForm.call(current_school, true)
  end

  def create
    form = 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 screenings
      current_employee.covid_screenings
    end

    def screening
      @screening ||= current_employee.covid_screenings.find_by(date: params[:date])
    end

    def questions
      current_school.covid_form_questions
        .where(id: params[:answers].pluck(:field_id))
        .by_employee_field(true)
    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
