class Admin::Admissions::CheckboxesController < Admin::Admissions::Controller
  def index
    data = checkboxes.by_archived(params[:archived]&.to_bool).sorted
    render_success :ok, json: data.map { |d| checklist_item_props(d) }
  end

  def show
    render_success :ok, json: checklist_item_props(checkbox)
  end

  def create
    checkbox = checkboxes.build(checkbox_params)
    if checkbox.save
      render_success :ok, json: checklist_item_props(checkbox)
    else
      render_error :unprocessable_entity, errors: checkbox
    end
  end

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

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

  private
    def checkboxes
      current_school.admission_checkboxes
    end

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

    def checkbox_params
      params.permit(:name, :description, :archived)
    end

    def checklist_item_props(checkbox)
      {}.tap do |props|
        props[:id] = checkbox.id
        props[:name] = checkbox.name
        props[:description] = checkbox.description
        props[:archived] = checkbox.archived
        return props if action_name.to_sym == :index

        props[:has_values] = checkbox.applicant_checkboxes.count
      end
    end
end
