"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadFileToR2 = exports.r2Client = void 0;
const client_s3_1 = require("@aws-sdk/client-s3");
const lib_storage_1 = require("@aws-sdk/lib-storage");
const dotenv_1 = __importDefault(require("dotenv"));
const fs_1 = __importDefault(require("fs"));
dotenv_1.default.config();
const accountId = process.env.R2_ACCOUNT_ID;
const accessKeyId = process.env.R2_ACCESS_KEY_ID;
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
const bucketName = process.env.R2_BUCKET_NAME;
const publicDomain = (_a = process.env.R2_PUBLIC_URL) === null || _a === void 0 ? void 0 : _a.replace(/\/$/, "");
if (!accountId || !accessKeyId || !secretAccessKey || !bucketName || !publicDomain) {
    throw new Error("Missing R2 credentials or Public Domain in .env");
}
exports.r2Client = new client_s3_1.S3Client({
    region: "auto",
    endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
    credentials: {
        accessKeyId,
        secretAccessKey,
    },
});
const uploadFileToR2 = (file) => __awaiter(void 0, void 0, void 0, function* () {
    const fileKey = `${Date.now()}-${encodeURIComponent(file.originalname.replace(/\s+/g, '-'))}`;
    try {
        // Use Upload from @aws-sdk/lib-storage for safer streaming
        const upload = new lib_storage_1.Upload({
            client: exports.r2Client,
            params: {
                Bucket: bucketName,
                Key: fileKey,
                Body: fs_1.default.createReadStream(file.path), // read from temp file
                ContentType: file.mimetype,
            },
            queueSize: 4,
            partSize: 5 * 1024 * 1024, // 5 MB
        });
        yield upload.done(); // completes the upload
        // Delete the temp file from server
        fs_1.default.unlink(file.path, (err) => {
            if (err)
                console.error("Failed to delete temp file:", err);
        });
        const publicUrl = `${publicDomain}/${fileKey}`;
        return {
            success: true,
            key: fileKey,
            url: publicUrl,
        };
    }
    catch (error) {
        console.error("R2 Upload Error:", error);
        // Delete temp file on error as well
        fs_1.default.unlink(file.path, (err) => {
            if (err)
                console.error("Failed to delete temp file:", err);
        });
        throw new Error("Failed to upload file to R2");
    }
});
exports.uploadFileToR2 = uploadFileToR2;
