"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportDatasetTemplateCsv = 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 exportDatasetTemplateCsv = async (req, res) => {
    try {
        const { id } = req.params;
        const projectId = req.query.projectId;
        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,
        })
            .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;
        }
        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 csv = (0, csvUtils_1.toCsv)(headers, []);
        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename="dataset-${dataset.name || dataset.id}-template.csv"`);
        res.status(200).send(csv);
    }
    catch (error) {
        logger_1.default.error(`Error exporting dataset template csv: ${error}`);
        res.status(500).json({ error: 'Failed to export dataset template csv' });
    }
};
exports.exportDatasetTemplateCsv = exportDatasetTemplateCsv;
//# sourceMappingURL=export-dataset-template-csv.js.map