import RPCClient from '@alicloud/pop-core';

interface TokenResponse {
  Token: {
    Id: string;
    ExpireTime: number;
  };
}
type AliCommonOptions = {
  accessKeyId: string;
  accessKeySecret: string;
};
export class AliCommon {
  private accessKeyId: string;
  private accessKeySecret: string;
  private endpoint: string;
  private apiVersion: string;
  token = '';
  expireTime = 0;
  constructor(opts?: AliCommonOptions) {
    this.accessKeyId = opts?.accessKeyId || process.env.ALIYUN_AK_ID || '';
    this.accessKeySecret = opts?.accessKeySecret || process.env.ALIYUN_AK_SECRET || '';
    this.endpoint = 'http://nls-meta.cn-shanghai.aliyuncs.com';
    this.apiVersion = '2019-02-28';
  }
  async getToken() {
    if (this.token && this.expireTime > Date.now()) {
      return this.token;
    }
    const client = new RPCClient({
      accessKeyId: this.accessKeyId,
      accessKeySecret: this.accessKeySecret,
      endpoint: this.endpoint,
      apiVersion: this.apiVersion,
    });

    const result = await client.request<TokenResponse>('CreateToken', {});
    this.token = result.Token.Id;
    this.expireTime = result.Token.ExpireTime * 1000;
    return result.Token.Id;
  }
}
