class PostsController < ApplicationController
  before_action :set_post, only: %i[show]

  # GET /posts
  def index
    post_scope = Post.published
    @pagy, @posts = pagy(post_scope.includes(:user).includes(:post_category).order("id DESC"), items: 10)
  end

  # GET /posts/1 or /posts/1.json
  def show
    read_flag = "post-#{@post.id}-read".to_sym
    if cookies[read_flag].blank?
      cookies[read_flag] = {value: Time.current.to_i.to_s, expires: 2.minutes}
      @post.increment!(:hit_count)
    end
  end

  private

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

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