"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateDatasetTable = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const uuid_1 = require("uuid");
const logger_1 = __importDefault(require("../../../logger"));
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const datasetRowsService_1 = require("../../services/datasetRows/datasetRowsService");
const updateDatasetTable = async (req, res) => {
    try {
        const { id } = req.params;
        const { data, fields, deletedRecordIds = [] } = req.body;
        const token = (req.headers['x-access-token'] || req.headers.authorization);
        if (!id || !data || !fields) {
            res.status(400).json({ error: 'Missing required parameters' });
            return;
        }
        const db = await (0, database_1.getDb)();
        if (!db) {
            res.status(500).json({ error: 'Database connection failed' });
            return;
        }
        const dataset = await db
            .select()
            .from(tables_1.trusysDatasetsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.id, id))
            .limit(1);
        if (!dataset[0]) {
            res.status(404).json({ error: 'Dataset not found' });
            return;
        }
        const ds = dataset[0];
        const datasetCached = {
            id: ds.id,
            name: String(ds.name ?? ''),
            fields: ds.fields,
            projectId: ds.projectId,
            workspaceId: ds.workspaceId,
            type: ds.type,
            config: ds.config,
        };
        await db
            .update(tables_1.trusysDatasetsTable)
            .set({
            fields,
        })
            .where((0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.id, id));
        if (deletedRecordIds.length > 0) {
            await db.delete(tables_1.datasetRecordsTable).where((0, drizzle_orm_1.inArray)(tables_1.datasetRecordsTable.id, deletedRecordIds));
        }
        for (const item of data) {
            const { _recordId, ...recordData } = item;
            if (_recordId) {
                const [existingRow] = await db
                    .select({ recordData: tables_1.datasetRecordsTable.recordData })
                    .from(tables_1.datasetRecordsTable)
                    .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.id, String(_recordId)), (0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.datasetId, id)))
                    .limit(1);
                if (!existingRow) {
                    res.status(404).json({ error: `Row not found: ${_recordId}` });
                    return;
                }
                const existingData = existingRow.recordData &&
                    typeof existingRow.recordData === 'object' &&
                    !Array.isArray(existingRow.recordData)
                    ? { ...existingRow.recordData }
                    : {};
                const mergedInput = { ...existingData, ...recordData };
                const { recordData: normalized } = await datasetRowsService_1.datasetRowsService.normalizeDatasetRecordForPersist({
                    datasetId: id,
                    token,
                    input: mergedInput,
                    mode: 'update',
                    existingRecordData: existingData,
                    datasetCached,
                });
                await db
                    .update(tables_1.datasetRecordsTable)
                    .set({
                    recordData: normalized,
                    updatedAt: new Date(),
                })
                    .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.id, String(_recordId)), (0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.datasetId, id)));
            }
            else {
                const { recordData: normalized } = await datasetRowsService_1.datasetRowsService.normalizeDatasetRecordForPersist({
                    datasetId: id,
                    token,
                    input: recordData,
                    mode: 'create',
                    datasetCached,
                });
                const newRecordId = (0, uuid_1.v4)();
                const maxRecord = await db
                    .select({ recordIndex: tables_1.datasetRecordsTable.recordIndex })
                    .from(tables_1.datasetRecordsTable)
                    .where((0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.datasetId, id))
                    .orderBy((0, drizzle_orm_1.desc)(tables_1.datasetRecordsTable.recordIndex))
                    .limit(1);
                const nextIndex = maxRecord.length > 0 ? maxRecord[0].recordIndex + 1 : 0;
                await db.insert(tables_1.datasetRecordsTable).values({
                    id: newRecordId,
                    datasetId: id,
                    recordData: normalized,
                    recordIndex: nextIndex,
                });
            }
        }
        res.json({ success: true });
    }
    catch (error) {
        logger_1.default.error(`Error updating dataset table: ${error}`);
        const status = typeof error?.status === 'number' ? error.status : 500;
        res.status(status).json({ error: error?.message || 'Failed to update dataset' });
    }
};
exports.updateDatasetTable = updateDatasetTable;
//# sourceMappingURL=update-dataset-table.js.map