class V1::UsersController < ApplicationController
  include ::FollowableController
  include ::DeletedObjectsController
  include ::Paginator


  before_action :set_user, only: [:show, :update, :destroy, :watching]
  before_action :authenticate_user!, only: [:create, :update, :destroy, :watching]

  # GET /v1/users
  # GET /v1/users.json
  def index
    users = paginate User
    render json: users
  end

  # GET /v1/users/1
  # GET /v1/users/1.json
  def show
    render json: @user
  end

  # POST /v1/users
  # POST /v1/users.json
  def create
    user = User.new(user_params)

    if user.save
      render json: user, status: :created
    else
      render json: user.errors, status: :unprocessable_entity
    end

  end

  # PUT/PATCH /v1/users/1
  # PUT/PATCH /v1/users/1.json
  def update
    if @user.update(user_params)
      render json: @user, status: :ok
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # DELETE /v1/users/1
  # DELETE /v1/users/1.json
  def destroy
    if current_user == @user
      render status: :forbidden
    else
      @user.destroy
      render status: :ok
    end
  end

  def watching
    type = params[:object_type]
    is_current = (@user.id == current_user.id) unless current_user.nil?
    return render status: :bad_request unless type.in? %w(User Collection)
    w = @user.watching(type, is_current)
    render json: w, root: 'follows', status: :ok
  end

  private

  def deleted_resource
    User
  end

  def followable
    set_user
  end

  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation, :terms_of_service, :avatar, role_ids: [])
  end
end