class Admin::Admissions::Applications::CheckboxesController < Admin::Admissions::Controller
  include Admin::Admissions::ApplicationScoped

  def index
    data = checkboxes.includes(:checkbox).order(:position).map { |c| checkbox_props(c) }
    render_success :ok, json: data
  end

  def create
    admissions_checkbox = admission_checkboxes.find(params[:checkbox_id])
    checkbox = checkboxes.build(checkbox: admissions_checkbox)
    if checkbox.save
      render_success :ok, json: checkbox_props(checkbox)
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  def update
    if checkbox.update(checkbox_params)
      render_success :ok, json: checkbox_props(checkbox)
    else
      render_error :unprocessable_entity, errors: checkbox
    end
  end

  def destroy
    if checkbox.destroy
      render_success :ok, event: :removed
    else
      render_error :unprocessable_entity, errors: checkbox
    end
  end

  private
    def checkboxes
      application.application_checkboxes
    end

    def checkbox
      @checkbox ||= checkboxes.find(params[:id])
    end

    def admission_checkboxes
      current_school.admission_checkboxes
    end

    def checkbox_params
      params.permit(:position, :internal)
    end

    def checkbox_props(checkbox)
      {
        id: checkbox.id,
        name: checkbox.checkbox.name,
        internal: checkbox.internal,
        position: checkbox.position,
        checkbox_id: checkbox.checkbox_id
      }
    end
end
