module Agent
  class ArticlesController < ApplicationController
    before_action :authenticate_user!
    before_action -> { authenticate_role!(:agent) }

    def index
      @articles = Article
      @articles = @articles.where(category_id: params[:categories]) if params[:categories]
      @articles = @articles.order(created_at: :desc).group_by(&:category_id)
    end

    def show
      @article = Article.find(params[:id])
    end

    def new
      @article = Article.new
    end

    def create
      @article = Article.create(article_params.merge(user: current_user))

      if @article.persisted?
        render turbo_stream: turbo_stream.update(:flash_messages, template: "agent/articles/create_success")
      else
        render :new, status: :unprocessable_entity
      end
    end

    def update
      @article = Article.find(params[:id])

      @article.update!(article_params)

      flash.now[:info] = t("shared.actions.saved")
      render turbo_stream: update_flash_messages_turbo_stream
    end

    private

    def article_params
      params.require(:article).permit(:category_id, :title, :content)
    end
  end
end
