module Youtube
  class OauthRefresh
    TOKEN_URL = "https://oauth2.googleapis.com/token".freeze

    def initialize(credential)
      @credential = credential
    end

    def apply!(service)
      refresh! if @credential.expired?
      service.authorization = @credential.access_token
      service
    end

    def refresh!
      response = Faraday.post(TOKEN_URL, {
        client_id: ENV["YOUTUBE_CLIENT_ID"],
        client_secret: ENV["YOUTUBE_CLIENT_SECRET"],
        refresh_token: @credential.refresh_token,
        grant_type: "refresh_token"
      })
      data = JSON.parse(response.body)
      raise Youtube::BroadcastService::Error, data["error"] if data["error"]

      @credential.update!(
        access_token: data["access_token"],
        expires_at: Time.current + data["expires_in"].to_i.seconds
      )
    end
  end
end
