# frozen_string_literal: true

class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.new(comment: params[:comment], user: current_user)
    if @comment.save
      (([@article.user] + @article.comments.map { |x| x.user }).uniq - [current_user]).each do |user|
        inbox = user.inboxes.create(article: @article, from_user: current_user, to_user: user, box_type: "Comment")
        InboxMailer.with(user: user, inbox: inbox).notify.deliver_later
      end
      respond_to do |format|
        # format.js { render @comment, content_type: "text/html" }
        format.html do
          flash[:success] = t("comment_added")
          redirect_to article_path(@article)
        end
      end
    else
      flash[:error] = t("bad_comment")
      redirect_to article_path(@article)
    end
  end
end
