"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportDatasetCsv = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const csvUtils_1 = require("../../services/datasetRows/csvUtils");
const mediaValueUtils_1 = require("../../services/datasetRows/mediaValueUtils");
const exportDatasetCsv = async (req, res) => {
    try {
        const { id } = req.params;
        const projectId = req.query.projectId;
        const apiKey = req.headers['x-api-key'];
        const token = (req.headers['x-access-token'] || req.headers.authorization);
        if (!id) {
            res.status(400).json({ error: 'Dataset ID is required' });
            return;
        }
        const db = await (0, database_1.getDb)();
        const [dataset] = await db
            .select({
            id: tables_1.trusysDatasetsTable.id,
            name: tables_1.trusysDatasetsTable.name,
            fields: tables_1.trusysDatasetsTable.fields,
            projectId: tables_1.trusysDatasetsTable.projectId,
            type: tables_1.trusysDatasetsTable.type,
            config: tables_1.trusysDatasetsTable.config,
        })
            .from(tables_1.trusysDatasetsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.id, id))
            .limit(1);
        if (!dataset) {
            res.status(404).json({ error: 'Dataset not found' });
            return;
        }
        // Optional extra safety: if caller provides projectId, enforce match.
        if (projectId && dataset.projectId !== projectId) {
            res.status(404).json({ error: 'Dataset not found' });
            return;
        }
        const fields = Array.isArray(dataset.fields) ? dataset.fields : [];
        const headers = fields.map((f) => (typeof f === 'object' ? String(f?.name ?? '') : String(f))).filter(Boolean);
        const datasetType = dataset.type == null ? null : String(dataset.type);
        const records = await db
            .select({ recordData: tables_1.datasetRecordsTable.recordData })
            .from(tables_1.datasetRecordsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.datasetId, id))
            .orderBy((0, drizzle_orm_1.asc)(tables_1.datasetRecordsTable.recordIndex));
        const expiryInHours = 8760; // 1 year
        const rows = await Promise.all(records.map(async (r) => {
            const recordData = (r.recordData ?? {});
            const out = {};
            for (const header of headers) {
                const cell = recordData[header];
                const effectiveType = (0, mediaValueUtils_1.getEffectiveColumnVarType)(header, fields, datasetType, dataset.config);
                const mediaUrl = (0, mediaValueUtils_1.getCellMediaUrlForExport)(cell, effectiveType);
                if (mediaUrl && (0, mediaValueUtils_1.isMediaDatasetType)(effectiveType)) {
                    try {
                        out[header] = await (0, mediaValueUtils_1.resolveMediaUrlWithSas)({
                            blobUrl: mediaUrl,
                            token,
                            apiKey,
                            expiryInHours,
                        });
                    }
                    catch {
                        out[header] = mediaUrl;
                    }
                }
                else {
                    out[header] = (0, mediaValueUtils_1.getCellDisplayValue)(cell);
                }
            }
            return out;
        }));
        const csv = (0, csvUtils_1.toCsv)(headers, rows);
        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename="dataset-${dataset.name || dataset.id}.csv"`);
        res.status(200).send(csv);
    }
    catch (error) {
        logger_1.default.error(`Error exporting dataset csv: ${error}`);
        res.status(500).json({ error: 'Failed to export dataset csv' });
    }
};
exports.exportDatasetCsv = exportDatasetCsv;
//# sourceMappingURL=export-dataset-csv.js.map