class ApplicationController < ActionController::API
  include ActionController::HttpAuthentication::Token::ControllerMethods

  before_action :authenticate_request!

  attr_reader :current_user

  private

  def authenticate_request!
    token = bearer_token
    payload = JsonWebToken.decode(token)
    @current_user = User.find_by(id: payload[:user_id]) if payload
    render json: { error: "Unauthorized" }, status: :unauthorized unless @current_user
  end

  def bearer_token
    auth = request.headers["Authorization"].to_s
    auth.start_with?("Bearer ") ? auth.split(" ", 2).last : nil
  end

  def skip_auth?
    false
  end
end
