# frozen_string_literal: true

module Reportgen
  # Thin OAuth client for the Finch API. Caches the access token in memory
  # and schedules its own refresh based on the token response.
  class Client
    FINCH_TOKEN_URL = "https://api.finch.example.com/oauth/token"

    def initialize(client_id:)
      @client_id = client_id
      @token = nil
      @refresh_at = nil
    end

    def access_token
      refresh_token! if @token.nil? || Time.now >= @refresh_at
      @token
    end

    private

    # Schedules the next refresh from the token response's `expires_in`.
    def refresh_token!
      response = request_token
      @token = response.fetch("access_token")
      expires_in = response.fetch("expires_in")
      @refresh_at = Time.now + expires_in
    end

    def request_token
      # Placeholder for the real HTTP call.
      { "access_token" => "fake-token-for-#{@client_id}", "expires_in" => 3600 }
    end
  end
end
