import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

// Cloudflare R2 credentials and settings from your .env
const accountId = process.env.R2_ACCOUNT_ID!;
const bucket = process.env.R2_BUCKET!;
const ttl = parseInt(process.env.SIGNED_URL_TTL_SECONDS || "120", 10);

const s3 = new S3Client({
  region: "auto",
  endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
  forcePathStyle: true,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
});

// Signs a temporary URL so the app can stream or download an audiobook securely
export async function signR2Url(hlsKey: string) {
  const cmd = new GetObjectCommand({ Bucket: bucket, Key: hlsKey });
  return await getSignedUrl(s3, cmd, { expiresIn: ttl });
}
