class Admin::PostsController < Admin::ApplicationController
  before_action :set_active_menu
  before_action :set_post, only: %i[show edit update destroy]

  # GET /admin/posts
  def index
    post_scope = Post
    if params[:category].present?
      post_scope = post_scope.where(post_category_id: params[:category])
    end
    if params[:user_id].present?
      post_scope = post_scope.where(user_id: params[:user_id])
    end
    @post_categories = PostCategory.order("position DESC").limit(25)
    @pagy, @posts = pagy(post_scope.includes(:user).includes(:post_category).order("id DESC"))
  end

  # GET /admin/posts/1
  def show
  end

  # GET /admin/posts/new
  def new
    @post = Post.new
  end

  # GET /admin/posts/1/edit
  def edit
  end

  # POST /admin/posts
  def create
    @post = current_user.posts.build(post_params)
    if params[:publish].present?
      @post.is_draft = false
      @post.published_at = Time.current
    end

    respond_to do |format|
      if @post.save
        format.html { redirect_to edit_admin_post_path(@post), notice: "Post was successfully created." }
      else
        format.html { render :new, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /admin/posts/1
  def update
    if params[:publish].present?
      if @post.is_draft?
        @post.is_draft = false
        @post.published_at = Time.current
      end
    else
      @post.is_draft = true
    end
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to edit_admin_post_path(@post), notice: "Post was successfully updated." }
      else
        format.html { render :edit, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /admin/posts/1
  def destroy
    audit! :delete_post, nil, payload: @post.attributes
    @post.destroy
    respond_to do |format|
      format.html { redirect_to admin_posts_path, notice: "Post was successfully destroyed." }
    end
  end

  private

  def set_active_menu
    @active_menu = "posts_manage"
  end

  # Use callbacks to share common setup or constraints between actions.
  def set_post
    @post = Post.find(params[:id])
  end

  # Only allow a list of trusted parameters through.
  def post_params
    params.require(:post).permit(:title, :content, :cover, :post_category_id)
  end
end
