import { PrivateOSSType } from '@bty/constant'
import { OSSClient } from './adapter/alioss'
import { MinIOAdapter } from './adapter/minio'
import type { STSTokenResponse } from './type'

export * from './type'

const StorageType = {
  AliOSS: PrivateOSSType.ALIYUN,
  MinIO: PrivateOSSType.MINIO,
} as const

type StorageType = (typeof StorageType)[keyof typeof StorageType]

function checkIsMinIOVersion() {
  try {
    return false
  } catch {
    return false
  }
}

const isMinIOVersion = checkIsMinIOVersion()

const STORAGE_TYPE: StorageType = isMinIOVersion
  ? StorageType.MinIO
  : StorageType.AliOSS

// 根据环境变量选择存储适配器
function getAdapterClass() {
  switch (STORAGE_TYPE) {
    case StorageType.MinIO:
      return MinIOAdapter
    case StorageType.AliOSS:
    default:
      return OSSClient
  }
}

// 获取适配器类
const AdapterClass = getAdapterClass()

// 导出工厂方法，根据环境变量创建相应的适配器实例
export function createCustomOSSUploader(
  tokenFn?: () => Promise<STSTokenResponse>,
) {
  return tokenFn
    ? AdapterClass.createCustomInstance(tokenFn)
    : AdapterClass.getInstance()
}

// 默认导出实例，根据环境变量选择适当的实现
export const ossUploader = AdapterClass.getInstance()
