# frozen_string_literal: true
module Admin
  class CommentController < AdminController
    def update
      comment = QuizComment.find_by(id: params[:id], test_hash: params[:test_hash])
      authorize comment

      comment.update(comment_params)
      flash_message = if comment.save
                        { success: "Sucessfully updated comment" }
                      else
                        { error: "Failed to update comment" }
                      end
      redirect_to admin_result_path(params[:test_hash]), flash: flash_message
    end

    def create
      comment = QuizComment.new(comment_params.merge(user_id: current_user.id, test_hash: params[:test_hash]))
      authorize comment

      flash_message = if comment.save
                        { success: "Sucessfully created comment" }
                      else
                        { error: "Failed to save comment" }
                      end

      ReviewerMailer.new_comment(comment).deliver_later if comment.persisted?
      redirect_to admin_result_path(params[:test_hash]), flash: flash_message
    end

    private

      def comment_params
        params.require(:quiz_comment).permit(:message)
      end
  end
end
