"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SqlExpressionResolverService = void 0;
const common_1 = require("@nestjs/common");
const chartjs_sql_data_provider_service_1 = require("./question-data-providers/chartjs-sql-data-provider.service");
const request_context_service_1 = require("./request-context.service");
const error_messages_1 = require("../constants/error-messages");
let SqlExpressionResolverService = class SqlExpressionResolverService {
    constructor(requestContextService) {
        this.requestContextService = requestContextService;
    }
    resolveSqlWithExpressions(sql, expressions) {
        const variableToColumnMap = {};
        const variablePattern = /{{\s*(\w+)\s*\[\s*([\w.]+)\s*\]\s*}}/g;
        let paramIndex = 1;
        const parameters = [];
        if (sql.includes('{{$activeUserId}}')) {
            const activeUser = this.requestContextService.getActiveUser();
            if (activeUser && activeUser.sub) {
                sql = sql.replace(/\{\{\$activeUserId\}\}/g, `$${paramIndex++}`);
                parameters.push(activeUser.sub);
            }
        }
        let simplifiedSql = sql.replace(variablePattern, (_, variableName, columnName) => {
            variableToColumnMap[variableName] = columnName;
            return `{{${variableName}}}`;
        });
        for (const expr of expressions) {
            const column = variableToColumnMap[expr.variableName];
            if (!column)
                continue;
            let sqlFragment = '';
            const placeholder = `{{${expr.variableName}}}`;
            switch (expr.operator) {
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.EQUALS:
                    sqlFragment = `${column} = $${paramIndex++}`;
                    parameters.push(expr.value[0]);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.NOT_EQUALS:
                    sqlFragment = `${column} != $${paramIndex++}`;
                    parameters.push(expr.value[0]);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.CONTAINS:
                    sqlFragment = `${column} LIKE $${paramIndex++}`;
                    parameters.push(`%${expr.value[0]}%`);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.NOT_CONTAINS:
                    sqlFragment = `${column} NOT LIKE $${paramIndex++}`;
                    parameters.push(`%${expr.value[0]}%`);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.STARTS_WITH:
                    sqlFragment = `${column} LIKE $${paramIndex++}`;
                    parameters.push(`${expr.value[0]}%`);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.ENDS_WITH:
                    sqlFragment = `${column} LIKE $${paramIndex++}`;
                    parameters.push(`%${expr.value[0]}`);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.IN:
                    const inParams = expr.value.map(val => {
                        parameters.push(val);
                        return `$${paramIndex++}`;
                    });
                    sqlFragment = `${column} IN (${inParams.join(", ")})`;
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.NOT_IN:
                    const notInParams = expr.value.map(val => {
                        parameters.push(val);
                        return `$${paramIndex++}`;
                    });
                    sqlFragment = `${column} NOT IN (${notInParams.join(", ")})`;
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.BETWEEN:
                    sqlFragment = `${column} BETWEEN $${paramIndex} AND $${paramIndex + 1}`;
                    parameters.push(expr.value[0], expr.value[1]);
                    paramIndex += 2;
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.LT:
                    sqlFragment = `${column} < $${paramIndex++}`;
                    parameters.push(expr.value[0]);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.LTE:
                    sqlFragment = `${column} <= $${paramIndex++}`;
                    parameters.push(expr.value[0]);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.GT:
                    sqlFragment = `${column} > $${paramIndex++}`;
                    parameters.push(expr.value[0]);
                    break;
                case chartjs_sql_data_provider_service_1.SqlExpressionOperator.GTE:
                    sqlFragment = `${column} >= $${paramIndex++}`;
                    parameters.push(expr.value[0]);
                    break;
                default:
                    throw new Error(error_messages_1.ERROR_MESSAGES.UNSUPPORTED_SQL_OPERATOR(expr.operator));
            }
            simplifiedSql = simplifiedSql.replace(placeholder, sqlFragment);
        }
        simplifiedSql = simplifiedSql.replace(/{{\s*\w+\s*}}/g, '');
        simplifiedSql = simplifiedSql.replace(/\bwhere\b\s*$/i, '').trim();
        return {
            rawSql: simplifiedSql,
            parameters
        };
    }
};
exports.SqlExpressionResolverService = SqlExpressionResolverService;
exports.SqlExpressionResolverService = SqlExpressionResolverService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [request_context_service_1.RequestContextService])
], SqlExpressionResolverService);
//# sourceMappingURL=sql-expression-resolver.service.js.map