import OSS from "ali-oss";

let _client: OSS | null = null;

function getOssConfig() {
  const region = process.env.OSS_REGION;
  const accessKeyId = process.env.OSS_ACCESS_KEY_ID;
  const accessKeySecret = process.env.OSS_ACCESS_KEY_SECRET;
  const bucket = process.env.OSS_BUCKET;
  const cdnDomain = process.env.OSS_CDN_DOMAIN;

  if (!region || !accessKeyId || !accessKeySecret || !bucket) {
    throw new Error(
      "[OSS] 缺少环境变量配置，请检查 OSS_REGION / OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET / OSS_BUCKET"
    );
  }

  return { region, accessKeyId, accessKeySecret, bucket, cdnDomain };
}

/**
 * 获取 OSS 客户端（懒加载，避免构建时因缺少环境变量报错）
 */
export function getOssClient(): OSS {
  if (!_client) {
    const { region, accessKeyId, accessKeySecret, bucket } = getOssConfig();
    _client = new OSS({
      region,
      accessKeyId,
      accessKeySecret,
      bucket,
    });
  }
  return _client;
}

/**
 * 获取 OSS bucket 名称
 */
export function getOssBucket(): string {
  return getOssConfig().bucket;
}

/**
 * 根据 OSS key 生成 CDN 加速访问 URL
 */
export function buildCdnUrl(ossKey: string): string {
  const { cdnDomain, bucket, region } = getOssConfig();
  if (cdnDomain) {
    return `${cdnDomain.replace(/\/$/, "")}/${ossKey}`;
  }
  // 如果没有配置 CDN，回退到 OSS 默认域名
  return `https://${bucket}.${region.replace("oss-", "oss-")}.aliyuncs.com/${ossKey}`;
}

/**
 * 生成 OSS 存储路径（key）
 * 格式：uploads/2026/07/17/<uuid>.<ext>
 */
export function generateOssKey(originalName: string): string {
  const ext = originalName.split(".").pop() ?? "";
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, "0");
  const d = String(now.getDate()).padStart(2, "0");
  const uuid = crypto.randomUUID();
  const suffix = ext ? `.${ext}` : "";
  return `uploads/${y}/${m}/${d}/${uuid}${suffix}`;
}
