class ManualSummariesController < ApplicationController
  load_and_authorize_resource :respondent_category
  load_and_authorize_resource through: :respondent_category

  before_action :set_manual_summary,
                except: %i[index new create]
  before_action :set_ancestors

  def show; end

  def index
    @manual_summaries = ManualSummary.all
  end

  def new
    @manual_summary = @respondent_category.manual_summaries.new
  end

  def edit; end

  def create
    @manual_summary = @respondent_category.manual_summaries.new(manual_summary_params)

    respond_to do |format|
      if @manual_summary.save
        format.html do
          redirect_to project_respondent_category_manual_summaries_path(@project, @respondent_category),
                      notice: "Summary was successfully created."
        end
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @manual_summary.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @manual_summary.update(manual_summary_params)
        format.html do
          redirect_to project_respondent_category_manual_summaries_path(@project, @respondent_category),
                      notice: "Summary was successfully updated."
        end
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @manual_summary.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @manual_summary.destroy!
    redirect_to project_respondent_category_manual_summaries_path(@project, @respondent_category),
                notice: "Summary deleted!"
  end

  private

  def set_manual_summary
    @manual_summary = ManualSummary.find(params[:id])
  end

  def set_ancestors
    @project = Project.find(params[:project_id])
    @respondent_category = RespondentCategory.find(params[:respondent_category_id])
  end

  def manual_summary_params
    params.require(:manual_summary).permit(:title, :respondent_category_id, :document)
  end
end
