import { request } from '@/http/request'
import { AESUtils } from '../utils/crypto'
import { tryParseToObject } from '../utils/parse'
import type { STSTokenResponse } from '../uploader/src/index'

export async function getSTSToken() {
  const env = process.env.NODE_ENV
  const encryptedData = await request.get<string | { data?: string }>('/oss/upload-sts')
  const dataToDecrypt = typeof encryptedData === 'string'
    ? encryptedData
    : encryptedData?.data

  if (typeof dataToDecrypt !== 'string') {
    throw new Error('Invalid encrypted STS payload')
  }

  const decryptedData = new AESUtils(env).decryptAES_CBC(dataToDecrypt)
  return tryParseToObject(decryptedData) as STSTokenResponse
}

export async function getOssSignatureUrl(key: string, params?: Record<string, unknown>) {
  const data = await request.post<
    string | {
      url?: string
      file_path?: string
    }
  >('/file/sign', {
    file_path: key,
    params,
  })
  if (typeof data === 'string' && data) {
    return data
  }
  if (data && typeof data === 'object') {
    return data.url || data.file_path || key
  }
  return key
}

export async function checkOssSignatureUrlIsExist() {
    // Basic check implementation or mock
    return true
}
