"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bulkAppendDatasetRowsPreview = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const logger_1 = __importDefault(require("../../../logger"));
const datasetBulkAppendService_1 = require("../../services/datasetRows/datasetBulkAppendService");
const bulkAppendDatasetRowsPreview = async (req, res) => {
    let extractPath;
    const file = req.file;
    try {
        const { id: datasetId } = req.params;
        const { projectId, orgId } = (req.body ?? {});
        if (!datasetId || !projectId || !orgId) {
            if (file?.path) {
                (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            }
            res.status(400).json({ error: 'datasetId, projectId and orgId are required' });
            return;
        }
        if (!file?.path) {
            res.status(400).json({ error: 'No file uploaded' });
            return;
        }
        const dataset = await (0, datasetBulkAppendService_1.loadDatasetForBulkAppend)(datasetId);
        if (!dataset) {
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            res.status(404).json({ error: 'Dataset not found' });
            return;
        }
        if (projectId && dataset.projectId !== projectId) {
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            res.status(404).json({ error: 'Dataset not found' });
            return;
        }
        const mode = (0, datasetBulkAppendService_1.resolveBulkAppendMode)(dataset);
        if (!mode) {
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            res.status(400).json({ error: 'Bulk upload is not supported for this dataset type' });
            return;
        }
        const ext = file.originalname.toLowerCase().endsWith('.zip')
            ? '.zip'
            : file.originalname.toLowerCase().endsWith('.csv')
                ? '.csv'
                : '';
        if (mode === 'zip' && ext !== '.zip') {
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            res.status(400).json({ error: 'This dataset requires a .zip file' });
            return;
        }
        if (mode === 'csv' && ext !== '.csv') {
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            res.status(400).json({ error: 'This dataset requires a .csv file' });
            return;
        }
        if (mode === 'zip') {
            const dataType = (0, datasetBulkAppendService_1.resolveDatasetUploadDataType)(dataset.config);
            let zipKind = null;
            if (dataType !== null) {
                zipKind = (0, datasetBulkAppendService_1.resolveZipKind)(dataType);
            }
            if (!zipKind) {
                (0, datasetBulkAppendService_1.cleanupFile)(file.path);
                res.status(400).json({ error: 'Unsupported upload data type for zip import' });
                return;
            }
            extractPath = await (0, datasetBulkAppendService_1.extractZipToDir)(file.path, path.resolve('temp_bulk_append'));
            const preview = (0, datasetBulkAppendService_1.previewZipContents)(extractPath, zipKind);
            (0, datasetBulkAppendService_1.cleanupDir)(extractPath);
            extractPath = undefined;
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
            if (preview.blockingError) {
                res.status(400).json({
                    success: false,
                    error: preview.blockingError,
                    fileName: file.originalname,
                    validCount: preview.validCount,
                    invalidCount: preview.invalidCount,
                    mode: 'zip',
                });
                return;
            }
            res.json({
                success: true,
                fileName: file.originalname,
                validCount: preview.validCount,
                invalidCount: preview.invalidCount,
                mode: 'zip',
            });
            return;
        }
        const csvText = fs.readFileSync(file.path, 'utf-8');
        const fields = Array.isArray(dataset.fields) ? dataset.fields : [];
        const preview = (0, datasetBulkAppendService_1.previewCsvForDataset)(csvText, fields);
        (0, datasetBulkAppendService_1.cleanupFile)(file.path);
        if (preview.headerError) {
            res.status(400).json({
                success: false,
                error: preview.headerError,
                fileName: file.originalname,
                validCount: 0,
                invalidCount: preview.invalidCount,
                mode: 'csv',
            });
            return;
        }
        res.json({
            success: true,
            fileName: file.originalname,
            validCount: preview.validCount,
            invalidCount: preview.invalidCount,
            mode: 'csv',
        });
    }
    catch (error) {
        logger_1.default.error(`bulkAppendDatasetRowsPreview: ${error}`);
        if (file?.path) {
            (0, datasetBulkAppendService_1.cleanupFile)(file.path);
        }
        if (extractPath) {
            (0, datasetBulkAppendService_1.cleanupDir)(extractPath);
        }
        const status = typeof error?.status === 'number' ? error.status : 500;
        res.status(status).json({ error: error?.message || 'Failed to preview bulk upload' });
    }
};
exports.bulkAppendDatasetRowsPreview = bulkAppendDatasetRowsPreview;
//# sourceMappingURL=bulk-append-dataset-rows-preview.js.map