class Api::V1::UsersController < ApplicationController
  before_action :set_user, only: %i[show update destroy]
  before_action :check_login, only: %i[index show]
  before_action :check_owner_or_admin, only: %i[update destroy]

  def index
    render json: UserSerializer.new(User.all).serializable_hash.to_json
  end

  def show
    if params[:included] === "true"
    options = { include: [:activities] }
    render json: UserSerializer.new(@user, options).serializable_hash.to_json
    else
    render json: UserSerializer.new(@user).serializable_hash.to_json
    end
  end

  def create
    @user = User.new(user_params)

    if @user.save
      render json: UserSerializer.new(@user).serializable_hash.to_json, status: :created
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  def update
    if @user.update(user_params)
      render json: UserSerializer.new(@user).serializable_hash.to_json, status: :ok
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @user.destroy
    head 204
  end

  private

  # Only allow a trusted parameter "white list" through.
  def user_params
    if current_user&.is_admin
      params.require(:user).permit(:email, :username, :password, :is_admin)
    else
      params.require(:user).permit(:email, :username, :password)
    end
  end

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

  def check_owner_or_admin
    head :forbidden unless @user.id == current_user&.id || current_user&.is_admin
  end
end