class Admin::Covid::Form::QuestionsController < Admin::Covid::Controller
  def index
    data = current_school.covid_form_questions.includes(:options)

    render_success :ok, json: data.map { |s| question_props(s) }
  end

  def show
    render_success :ok, json: question_props(question)
  end

  def create
    @question = questions.build(question_params)
    set_options if question.has_options?

    if question.save
      render_success :ok, json: question_props(question)
    else
      render_error :unprocessable_entity, errors: question
    end
  end

  def update
    question.assign_attributes(question_params)
    set_options if question.has_options?

    if question.save
      render_success :ok, json: question_props(question)
    else
      render_error :unprocessable_entity, errors: question
    end
  end

  def destroy
    if question.destroy
      render_success :ok
    else
      render_error :unprocessable_entity
    end
  end

  private
    def questions
      section.questions
    end

    def question
      @question ||= questions.find_by(id: params[:id])
    end

    def section
      @section ||= current_school.covid_form_sections.find_by(id: params[:section_id])
    end

    def set_options
      return if params[:options].blank?

      params[:options].each do |option|
        update_option = question.options.find_by(id: option[:id]) || question.options.build
        update_option.assign_attributes(option_params(option))
      end
    end

    def question_params
      params.permit(
        :title,
        :description,
        :field,
        :sequence,
        :required,
        options_attributes: [:id, :sequence, :value, :_destroy]
      )
    end

    def option_params(option)
      option.permit(:value, :sequence)
    end

    def option_props(option)
      {
        id: option.id,
        value: option.value,
        sequence: option.sequence
      }
    end

    def question_props(question)
      {}.tap do |props|
        props[:id] = question.id
        props[:section_id] = question.section_id
        props[:type] = question.type
        props[:title] = question.title
        props[:description] = question.description
        props[:field] = question.field
        props[:required] = question.required
        props[:sequence] = question.sequence
        props[:options] = question.options.map { |o| option_props(o) } if question.has_options?
      end
    end
end
