class SubmissionsController < ApplicationController
  before_action :set_submission, only: %i[ moderate ]
  after_action :verify_authorized, except: [ :index ]
  after_action :verify_policy_scoped, only: [ :index ]

  # GET /submissions or /submissions.json
  # Shows pending submissions for moderation
  def index
    @submissions = policy_scope(Submission, policy_scope_class: SubmissionPolicy::ModerationScope)
                     .pending
                     .includes(:content, :feed, content: :user)
                     .order(created_at: :asc)
  end

  # PATCH /submissions/1/moderate
  def moderate
    authorize @submission

    status = moderation_params[:moderation_status]
    reason = moderation_params[:moderation_reason]

    unless %w[approved rejected].include?(status)
      return respond_to do |format|
        format.html { redirect_back_or_to submissions_path, allow_other_host: false, alert: "Invalid moderation action." }
        format.json { render json: { error: "Invalid moderation action" }, status: :bad_request }
      end
    end

    @submission.moderate!(status: status, moderator: current_user, reason: reason)

    respond_to do |format|
      format.html { redirect_back_or_to submissions_path, allow_other_host: false, notice: "Submission was #{status}." }
      format.json { render json: @submission, status: :ok }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_submission
      @submission = Submission.find(params[:id])
    end

    def moderation_params
      params.require(:submission).permit(policy(@submission).permitted_attributes_for_moderation)
    end
end
