class Admin::Covid::Form::SectionsController < Admin::Covid::Controller
  def index
    data = sections.includes(:fields).by_employee_field(params[:employee_field]&.to_bool).ordered
    render_success :ok, json: data.map { |s| section_props(s) }
  end

  def show
    render_success :ok, json: section_props(section)
  end

  def create
    section = sections.build(section_params)

    if section.save
      render_success :ok, json: section_props(section)
    else
      render_error :unprocessable_entity, errors: section
    end
  end

  def update
    if section.update(section_params)
      render_success :ok, json: section_props(section)
    else
      render_error :unprocessable_entity, errors: section
    end
  end

  def destroy
    if section.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: section
    end
  end

  def batch_update
    updates = []

    sections.where(id: params[:ids]).each do |section|
      sequence = params[:sections].find { |i| i[:id] == section.id }[:sequence]
      section.assign_attributes(sequence: sequence)
      updates << section
    end

    if transactional_save(updates)
      render_success :ok, message: 'Sections Updated'
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  private
    def sections
      current_school.covid_form_sections
    end

    def section
      @section ||= sections.find_by(id: params[:id])
    end

    def section_params
      params.permit(:title, :description, :sequence, :employee_field)
    end

    def section_props(section)
      {
        id: section.id,
        title: section.title,
        description: section.description,
        sequence: section.sequence,
        fields: section.fields
      }
    end
end
