const COS = require('cos-nodejs-sdk-v5')
const config = require('../config')

let client

function getClient() {
  if (!client) {
    client = new COS({
      SecretId: config.cos.secretId,
      SecretKey: config.cos.secretKey
    })
  }
  return client
}

function getObjectUrl(key, expiresSeconds) {
  return new Promise((resolve, reject) => {
    getClient().getObjectUrl({
      Bucket: config.cos.bucket,
      Region: config.cos.region,
      Key: key,
      Sign: true,
      Expires: expiresSeconds || 3600
    }, (err, data) => {
      if (err) reject(err)
      else resolve(data.Url)
    })
  })
}

module.exports = { getClient, getObjectUrl }
