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

const isDev = process.env.NODE_ENV === "development";

function getR2Client() {
  return 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 DEV_BASE_URL = process.env.NEXTAUTH_URL ?? "http://localhost:3000";

export async function generateUploadUrl(
  key: string,
  contentType: string,
  expiresIn = 300
): Promise<string> {
  if (isDev) {
    return `${DEV_BASE_URL}/api/files/dev/${key}`;
  }
  const command = new PutObjectCommand({
    Bucket: process.env.R2_BUCKET_NAME!,
    Key: key,
    ContentType: contentType,
  });
  return getSignedUrl(getR2Client(), command, { expiresIn });
}

export async function generateDownloadUrl(
  key: string,
  expiresIn = 3600
): Promise<string> {
  if (isDev) {
    return `${DEV_BASE_URL}/api/files/dev/${key}`;
  }
  const command = new GetObjectCommand({ Bucket: process.env.R2_BUCKET_NAME!, Key: key });
  return getSignedUrl(getR2Client(), command, { expiresIn });
}

export function buildStorageKey(
  type: "po-document" | "receipt",
  poId: string,
  fileName: string
): string {
  const timestamp = Date.now();
  const safe = fileName.replace(/[^a-zA-Z0-9._-]/g, "_");
  return `${type}/${poId}/${timestamp}-${safe}`;
}
