/**
 * Cloudflare R2 settings for release package delivery.
 *
 * Read lazily from the environment on every call: nothing here may throw at
 * module load, because the update router is imported by every server test.
 */

export type R2Config = {
  endpoint: string;
  bucket: string;
  region: string;
  accessKeyId: string;
  secretAccessKey: string;
  signedUrlTtlSeconds: number;
};

const DEFAULT_TTL_SECONDS = 300;

export function getR2Config(): R2Config | null {
  const endpoint = process.env.R2_ACCOUNT_ENDPOINT;
  const bucket = process.env.R2_BUCKET;
  const accessKeyId = process.env.R2_ACCESS_KEY_ID;
  const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;

  if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) {
    return null;
  }

  const ttl = Number.parseInt(process.env.R2_SIGNED_URL_TTL_SECONDS ?? '', 10);

  return {
    endpoint,
    bucket,
    region: process.env.R2_REGION || 'auto',
    accessKeyId,
    secretAccessKey,
    signedUrlTtlSeconds: Number.isFinite(ttl) && ttl > 0 ? ttl : DEFAULT_TTL_SECONDS,
  };
}
