import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import crypto from 'crypto'

const s3Client = new S3Client({
  region: 'auto',
  endpoint: process.env.R2_ENDPOINT,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
})

const BUCKET_NAME = process.env.R2_BUCKET_NAME!

export async function uploadBase64Image(
  base64Data: string,
  fileName: string,
  contentType: string = 'image/png'
): Promise<string> {
  // 移除data URL前缀
  const base64Content = base64Data.replace(/^data:image\/[a-z]+;base64,/, '')
  const buffer = Buffer.from(base64Content, 'base64')
  
  // 生成唯一的文件路径
  const timestamp = Date.now()
  const hash = crypto.createHash('md5').update(buffer).digest('hex').slice(0, 8)
  const filePath = `generated-images/${timestamp}-${hash}-${fileName}`
  
  const command = new PutObjectCommand({
    Bucket: BUCKET_NAME,
    Key: filePath,
    Body: buffer,
    ContentType: contentType,
    ContentDisposition: 'inline',
  })
  
  await s3Client.send(command)
  return filePath
}

export async function getSignedImageUrl(filePath: string, expiresIn: number = 3600): Promise<string> {
  const command = new GetObjectCommand({
    Bucket: BUCKET_NAME,
    Key: filePath,
  })
  
  return await getSignedUrl(s3Client, command, { expiresIn })
}