"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigrationController = void 0;
const logger_1 = __importDefault(require("../../../logger"));
const guardrailReferenceTablesClickhouse_1 = require("../../services/argus/tools/guardrailReferenceTablesClickhouse");
const clickhouseSchemaService_1 = require("../../services/clickhouseSchemaService");
const evalResultsPostgresToClickhouseSync_1 = require("../../services/evalResultsPostgresToClickhouseSync");
const migrationService_1 = require("../../services/migrationService");
const MigrationController = {
    async migrateApplicationsToClickhouse(req, res) {
        try {
            logger_1.default.info('Migrate Applications to ClickHouse endpoint called');
            const result = await migrationService_1.migrationService.migrateApplicationsToClickhouse();
            res.json({ success: true, data: result });
        }
        catch (error) {
            logger_1.default.error(`Error in migrate applications to clickhouse controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to migrate applications to ClickHouse',
                error: error.message,
            });
        }
    },
    async migrateProjectId(req, res) {
        try {
            logger_1.default.info('Migrate Project ID endpoint called');
            const { oldProjectId, newProjectId } = req?.body ?? {};
            if (!oldProjectId || !newProjectId) {
                res.status(400).json({
                    success: false,
                    message: 'Both oldProjectId and newProjectId are required',
                    error: 'Missing required parameters',
                });
                return;
            }
            if (oldProjectId === newProjectId) {
                res.status(400).json({
                    success: false,
                    message: 'oldProjectId and newProjectId cannot be the same',
                    error: 'Invalid parameters',
                });
                return;
            }
            const result = await migrationService_1.migrationService.migrateProjectId({
                oldProjectId: oldProjectId,
                newProjectId: newProjectId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in migrate project ID controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to migrate project ID',
                error: error.message,
            });
        }
    },
    async migrateDatasetRecords(req, res) {
        try {
            logger_1.default.info('Migrate Dataset Records endpoint called');
            const result = await migrationService_1.migrationService.migrateDatasetRecords();
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in migrate dataset records controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to migrate dataset records',
                error: error.message,
            });
        }
    },
    async addProjectId(req, res) {
        try {
            logger_1.default.info('Add Project ID endpoint called');
            const result = await migrationService_1.migrationService.addProjectId();
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in add project ID controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to add project ID',
                error: error.message,
            });
        }
    },
    async addClickhouseColumn(req, res) {
        const expectedSecret = process.env.CLICKHOUSE_SCHEMA_ADMIN_SECRET;
        if (expectedSecret) {
            const provided = req.headers['x-clickhouse-schema-secret'];
            if (provided !== expectedSecret) {
                res.status(403).json({
                    success: false,
                    message: 'Forbidden: invalid or missing x-clickhouse-schema-secret',
                });
                return;
            }
        }
        try {
            const body = req.body ?? {};
            const tableName = typeof body.tableName === 'string' ? body.tableName : '';
            let columnName = typeof body.columnName === 'string' ? body.columnName.trim() : '';
            let columnType = typeof body.columnType === 'string' ? body.columnType.trim() : '';
            const field = typeof body.field === 'string' ? body.field.trim() : '';
            if (!columnName && field) {
                const fieldMatch = /^([a-zA-Z_][a-zA-Z0-9_]*)\s+(.+)$/u.exec(field);
                if (!fieldMatch) {
                    res.status(400).json({
                        success: false,
                        message: 'Provide columnName and columnType, or field as "<column_name> <clickhouse_type>" (e.g. test_run_id Nullable(String))',
                    });
                    return;
                }
                columnName = fieldMatch[1];
                columnType = fieldMatch[2].trim();
            }
            if (!tableName || !columnName || !columnType) {
                res.status(400).json({
                    success: false,
                    message: 'tableName, columnName, and columnType are required (or tableName + field)',
                });
                return;
            }
            const afterColumn = typeof body.afterColumn === 'string' && body.afterColumn.trim() !== ''
                ? body.afterColumn.trim()
                : undefined;
            logger_1.default.info('Add ClickHouse column endpoint called');
            const result = await clickhouseSchemaService_1.clickhouseSchemaService.addColumnIfNotExists({
                tableName,
                columnName,
                columnType,
                afterColumn,
            });
            res.json({ success: true, data: result });
        }
        catch (error) {
            logger_1.default.error(`Error in add ClickHouse column: ${error}`);
            const isValidation = error instanceof clickhouseSchemaService_1.ClickHouseSchemaValidationError;
            res.status(isValidation ? 400 : 500).json({
                success: false,
                message: isValidation ? 'Invalid request' : 'Failed to add ClickHouse column',
                error: error.message,
            });
        }
    },
    async syncEvalResultsFromPostgresToClickhouse(req, res) {
        const expectedSecret = process.env.CLICKHOUSE_SCHEMA_ADMIN_SECRET;
        if (expectedSecret) {
            const provided = req.headers['x-clickhouse-schema-secret'];
            if (provided !== expectedSecret) {
                res.status(403).json({
                    success: false,
                    message: 'Forbidden: invalid or missing x-clickhouse-schema-secret',
                });
                return;
            }
        }
        try {
            const body = req.body ?? {};
            const batchSize = typeof body.batchSize === 'number' && Number.isFinite(body.batchSize)
                ? body.batchSize
                : undefined;
            const maxBatches = typeof body.maxBatches === 'number' && Number.isFinite(body.maxBatches)
                ? body.maxBatches
                : undefined;
            logger_1.default.info('Sync Postgres eval_results -> ClickHouse eval_results called');
            const result = await (0, evalResultsPostgresToClickhouseSync_1.syncEvalResultsFromPostgresToClickhouse)({ batchSize, maxBatches });
            res.json({ success: true, data: result });
        }
        catch (error) {
            logger_1.default.error(`Error syncing eval_results to ClickHouse: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to sync eval_results from Postgres to ClickHouse',
                error: error.message,
            });
        }
    },
    async syncGuardrailCatalog(req, res) {
        const expectedSecret = process.env.CLICKHOUSE_SCHEMA_ADMIN_SECRET;
        if (expectedSecret) {
            const provided = req.headers['x-clickhouse-schema-secret'];
            if (provided !== expectedSecret) {
                res.status(403).json({
                    success: false,
                    message: 'Forbidden: invalid or missing x-clickhouse-schema-secret',
                });
                return;
            }
        }
        try {
            logger_1.default.info('Sync ClickHouse guardrail catalog (validators, categories, actions) called');
            const result = await (0, guardrailReferenceTablesClickhouse_1.syncGuardrailReferenceTablesFromSeed)();
            res.json({ success: true, data: result });
        }
        catch (error) {
            logger_1.default.error(`Error syncing ClickHouse guardrail catalog: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to sync ClickHouse guardrail catalog',
                error: error.message,
            });
        }
    },
    async copyPromptsBetweenLibraries(req, res) {
        try {
            logger_1.default.info('Copy Prompts Between Libraries endpoint called');
            const { sourceLibraryId, targetLibraryId } = req?.body ?? {};
            if (!sourceLibraryId || !targetLibraryId) {
                res.status(400).json({
                    success: false,
                    message: 'Both sourceLibraryId and targetLibraryId are required',
                    error: 'Missing required parameters',
                });
                return;
            }
            if (sourceLibraryId === targetLibraryId) {
                res.status(400).json({
                    success: false,
                    message: 'sourceLibraryId and targetLibraryId cannot be the same',
                    error: 'Invalid parameters',
                });
                return;
            }
            const result = await migrationService_1.migrationService.copyPromptsBetweenLibraries({
                sourceLibraryId: sourceLibraryId,
                targetLibraryId: targetLibraryId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in copy prompts between libraries controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to copy prompts between libraries',
                error: error.message,
            });
        }
    },
};
exports.MigrationController = MigrationController;
//# sourceMappingURL=index.js.map