class PostsController < ApplicationController

  before_action :load_post, only: [:show, :edit, :update]
  before_action :authenticate_user!, only: [:edit, :update, :destroy]
  before_action :check_owner, only: [:edit, :update, :destroy]

  def index
    @blogger = User.find params[:user_id]
    @posts = Post.where("user_id = ?", @blogger.id)
  end

  def create
    @post = Post.new(post_params.merge(user_id: params[:user_id]))
    if @post.save
      flash[:notice] = "Post successfully created"
      redirect_to user_posts_path(current_user)
    else
      render :new
    end
  end

  def update
    if @post.update!(post_params)
      flash[:notice] = "Post successfully updated"
      redirect_to root_path
    else
      render :edit
    end
  end

  private

  def load_post
    @post = Post.find(params[:id])
  end

  def check_owner
    if current_user != @post.user
      return redirect_to root_path
    end
  end

  def post_params
    params.require(:post).permit(:title, :content)
  end

end
