"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadDatasetSourceDocuments = void 0;
const path = __importStar(require("node:path"));
const uploadFilesToAzure_1 = require("../../../util/uploadFilesToAzure");
/**
 * Uploads dataset source documents to Azure for evaluation-time synthesis (generateOnEvaluation + documents).
 * Returns SAS-backed URLs to persist in dataset config as `documentSources`.
 */
const uploadDatasetSourceDocuments = async (req, res) => {
    try {
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const orgId = String(req.body?.orgId ?? '').trim();
        const projectId = String(req.body?.projectId ?? '').trim();
        const stagingId = String(req.body?.stagingId ?? '').trim();
        if (!orgId || !projectId || !stagingId) {
            res.status(400).json({ error: 'orgId, projectId, and stagingId are required' });
            return;
        }
        const files = req.files;
        if (!Array.isArray(files) || files.length === 0) {
            res.status(400).json({ error: 'At least one document file is required' });
            return;
        }
        const folder = `workspace/${orgId}/project/${projectId}/dataset-document-sources/${stagingId}`;
        const uploadItems = files.map((f, index) => {
            const diskPath = f.path;
            const original = f.originalname || path.basename(diskPath);
            const ext = path.extname(original) || '.bin';
            const safeBase = path.basename(original, ext).replace(/[^\w.\-]+/g, '_') || 'document';
            const fileName = `${index}-${safeBase}${ext}`;
            const mime = f.mimetype || 'application/octet-stream';
            return {
                filePath: diskPath,
                fileName,
                contentType: mime,
                cleanupAfterUpload: true,
                privateContainer: true,
                generateSasToken: true,
            };
        });
        const urlMap = await (0, uploadFilesToAzure_1.uploadFilesToAzure)(uploadItems, token, folder);
        const documentSources = uploadItems.map((item, index) => {
            const f = files[index];
            const original = f.originalname || path.basename(f.path);
            const url = urlMap[item.fileName] || '';
            return { name: original, fileName: item.fileName, url };
        });
        const missing = documentSources.filter((d) => !d.url);
        if (missing.length > 0) {
            res.status(500).json({ error: 'Upload completed but some blob URLs are missing' });
            return;
        }
        res.status(200).json({ documentSources });
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        res.status(500).json({ error: 'Failed to upload source documents', details: message });
    }
};
exports.uploadDatasetSourceDocuments = uploadDatasetSourceDocuments;
//# sourceMappingURL=upload-dataset-source-documents.js.map