import { S3Client, PutObjectCommand, DeleteObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; const r2Client = new S3Client({ region: 'auto', endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`, credentials: { accessKeyId: process.env.R2_ACCESS_KEY_ID, secretAccessKey: process.env.R2_SECRET_ACCESS_KEY, }, }); const BUCKET = process.env.R2_BUCKET_NAME || 'woodlands-supermarket'; const PUBLIC_URL = process.env.R2_PUBLIC_URL || ''; export const uploadToR2 = async (buffer, key, contentType) => { await r2Client.send(new PutObjectCommand({ Bucket: BUCKET, Key: key, Body: buffer, ContentType: contentType, CacheControl: 'public, max-age=31536000', })); return { key, url: PUBLIC_URL ? `${PUBLIC_URL}/${key}` : `/api/upload/file/${encodeURIComponent(key)}`, }; }; export const deleteFromR2 = async (key) => { await r2Client.send(new DeleteObjectCommand({ Bucket: BUCKET, Key: key })); }; export const getSignedDownloadUrl = async (key, expiresIn = 3600) => { const command = new GetObjectCommand({ Bucket: BUCKET, Key: key }); return getSignedUrl(r2Client, command, { expiresIn }); }; export default r2Client;