import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import COS from 'cos-js-sdk-v5';

/**
 * COS临时凭证响应
 */
export interface CosCredentialResponse {
  credentials: {
    tmpSecretId: string;
    tmpSecretKey: string;
    sessionToken: string;
  };
  startTime: number;
  expiredTime: number;
  expiration: string;
}

/**
 * COS配置响应
 */
export interface CosConfigResponse {
  bucket: string;
  region: string;
}

/**
 * 获取COS临时凭证
 */
export const getCosCredential = (): AxiosPromise<CosCredentialResponse> => {
  return request({
    url: '/inspection/cos/credential',
    method: 'get'
  });
};

/**
 * 获取COS配置信息
 */
export const getCosConfig = (): AxiosPromise<CosConfigResponse> => {
  return request({
    url: '/inspection/cos/config',
    method: 'get'
  });
};

/**
 * 创建COS实例(包含自动获取凭证)
 */
export const createCosInstance = (): COS => {
  return new COS({
    getAuthorization: (options, callback) => {
      getCosCredential()
        .then((res) => {
          const credentials = res.data.credentials;
          callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            SecurityToken: credentials.sessionToken,
            StartTime: res.data.startTime,
            ExpiredTime: res.data.expiredTime
          });
        })
        .catch((error) => {
          console.error('获取COS临时凭证失败:', error);
        });
    }
  });
};
