"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateDatasetRow = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const constants_1 = require("../../../constants");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const activityLogService_1 = require("../../services/activityLogService");
const datasetRowsService_1 = require("../../services/datasetRows/datasetRowsService");
const dataset_row_files_middleware_1 = require("./dataset-row-files-middleware");
const parse_dataset_row_request_1 = require("./parse-dataset-row-request");
const updateDatasetRow = async (req, res) => {
    const uploadedFiles = req.files;
    try {
        const { id: datasetId, recordId } = req.params;
        const token = (req.headers['x-access-token'] || req.headers.authorization);
        const parsed = (0, parse_dataset_row_request_1.parseDatasetRowPayload)(req);
        if (parsed.parseError) {
            res.status(400).json({ error: parsed.parseError });
            return;
        }
        const { projectId, orgId, row } = parsed;
        if (!datasetId || !recordId || !projectId || !orgId || !row) {
            res.status(400).json({ error: 'datasetId, recordId, projectId, orgId and row are required' });
            return;
        }
        const filesByField = (0, parse_dataset_row_request_1.getUploadedFilesByField)(req);
        const updated = await datasetRowsService_1.datasetRowsService.updateRow({
            datasetId,
            recordId,
            token,
            input: row,
            filesByField,
        });
        try {
            const db = await (0, database_1.getDb)();
            const [dataset] = await db
                .select({ name: tables_1.trusysDatasetsTable.name })
                .from(tables_1.trusysDatasetsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.id, datasetId))
                .limit(1);
            const datasetName = dataset?.name || datasetId;
            const { userId, userName } = (0, activityLogService_1.getUserInfo)(req);
            const [orgName, projectName] = await Promise.all([
                (0, activityLogService_1.fetchOrgName)(token, orgId),
                (0, activityLogService_1.fetchProjectName)(token, orgId, projectId),
            ]);
            await (0, activityLogService_1.logActivity)(token, {
                type: constants_1.ActivityType.UPDATE_DATASET,
                params: (0, activityLogService_1.buildActivityParams)({
                    dataset_name: { value: datasetName, _id: datasetId },
                    user_name: { value: userName, _id: userId },
                    org_name: { value: orgName || orgId, _id: orgId },
                    project_name: { value: projectName || projectId, _id: projectId },
                    message: { value: `Dataset row updated in dataset-${datasetName} by ${userName}` },
                }),
                project_id: projectId,
                org_id: orgId,
                created_by: userId,
                updated_by: userId,
            });
        }
        catch (activityError) {
            logger_1.default.error(`Error logging activity for update dataset row: ${activityError}`);
        }
        res.json({
            success: true,
            row: {
                ...updated.recordData,
                _recordId: updated.recordId,
            },
        });
    }
    catch (error) {
        const status = typeof error?.status === 'number' ? error.status : 500;
        logger_1.default.error(`Error updating dataset row: ${error}`);
        res.status(status).json({ error: error?.message || 'Failed to update dataset row' });
    }
    finally {
        (0, dataset_row_files_middleware_1.cleanupMulterFiles)(uploadedFiles);
    }
};
exports.updateDatasetRow = updateDatasetRow;
//# sourceMappingURL=update-dataset-row.js.map