'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.evaluateSQL = evaluateSQL;
exports.checkASTPermissions = checkASTPermissions;
exports.convertSQLToAST = convertSQLToAST;
exports.processAST = processAST;
const insert = __importStar(require("../dataLayer/insert.js"));
const util = __importStar(require("util"));
const cbInsertInsert = util.callbackify(insert.insert);
const search_ts_1 = require("../dataLayer/search.js");
const update_ts_1 = require("../dataLayer/update.js");
const cbUpdateUpdate = util.callbackify(update_ts_1.update);
const deleteTranslator_ts_1 = require("./deleteTranslator.js");
const cbDeleteTranslator = util.callbackify(deleteTranslator_ts_1.convertDelete);
const alasql = __importStar(require("alasql"));
const opAuth = __importStar(require("../utility/operation_authorization.js"));
const harper_logger_ts_1 = __importDefault(require("../utility/logging/harper_logger.js"));
const alasqlFunctionImporter_ts_1 = __importDefault(require("./alasqlFunctionImporter.js"));
const hdbUtils = __importStar(require("../utility/common_utils.js"));
const terms = __importStar(require("../utility/hdbTerms.js"));
const hdbError_ts_1 = require("../utility/errors/hdbError.js");
const commonErrors_ts_1 = require("../utility/errors/commonErrors.js");
//here we call to define and import custom functions to alasql
(0, alasqlFunctionImporter_ts_1.default)(alasql);
let UNAUTHORIZED_RESPONSE = 403;
const SQL_INSERT_ERROR_MSG = 'There was a problem performing this insert. Please check the logs and try again.';
class ParsedSQLObject {
    ast;
    variant;
    permissions_checked;
    constructor() {
        this.ast = undefined;
        this.variant = undefined;
        this.permissions_checked = false;
    }
}
function evaluateSQL(jsonMessage, callback) {
    let parsedSql = jsonMessage.parsed_sql_object;
    if (!parsedSql) {
        parsedSql = convertSQLToAST(jsonMessage.sql);
        //TODO; This is a temporary check and should be removed once validation is integrated.
        let schema = undefined;
        let statement = parsedSql.ast.statements[0];
        if (statement instanceof alasql.yy.Insert) {
            schema = statement.into.databaseid;
        }
        else if (statement instanceof alasql.yy.Select) {
            schema = statement.from ? statement.from[0].databaseid : null;
        }
        else if (statement instanceof alasql.yy.Update) {
            schema = statement.table.databaseid;
        }
        else if (statement instanceof alasql.yy.Delete) {
            schema = statement.table.databaseid;
        }
        else {
            harper_logger_ts_1.default.error(`AST in evaluateSQL is not a valid SQL type.`);
        }
        if (!(statement instanceof alasql.yy.Select) && hdbUtils.isEmptyOrZeroLength(schema)) {
            return callback('No schema specified', null);
        }
    }
    processAST(jsonMessage, parsedSql, (error, results) => {
        if (error) {
            return callback(error);
        }
        callback(null, results);
    });
}
/**
 * Provides a direct path to checking permissions for a given AST.  Returns false if permissions check fails.
 * @param jsonMessage - The JSON inbound message.
 * @param parsedSqlObject - The Parsed SQL statement specified in the inbound json message, of type ParsedSQLObject.
 * @returns {Array} - False if permissions check denys the statement.
 */
function checkASTPermissions(jsonMessage, parsedSqlObject) {
    let verifyResult = undefined;
    try {
        verifyResult = opAuth.verifyPermsAST(parsedSqlObject.ast.statements[0], jsonMessage.hdb_user, parsedSqlObject.variant);
        parsedSqlObject.permissions_checked = true;
    }
    catch (e) {
        throw e;
    }
    if (verifyResult) {
        return verifyResult;
    }
    return null;
}
function convertSQLToAST(sql) {
    let astResponse = new ParsedSQLObject();
    if (!sql) {
        throw (0, hdbError_ts_1.handleHDBError)(new Error(), "The 'sql' parameter is missing from the request body", commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST);
    }
    try {
        let trimmedSql = sql.trim();
        let ast = alasql.parse(trimmedSql);
        let variant = trimmedSql.split(' ')[0].toLowerCase();
        astResponse.ast = ast;
        astResponse.variant = variant;
    }
    catch (e) {
        let splitError = e.message.split('\n');
        if (splitError[1]) {
            throw (0, hdbError_ts_1.handleHDBError)(e, `Invalid SQL at: ${splitError[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`, commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST);
        }
        else {
            throw (0, hdbError_ts_1.handleHDBError)(e, `We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`, commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST);
        }
    }
    return astResponse;
}
function processAST(jsonMessage, parsedSqlObject, callback) {
    try {
        let sqlFunction = nullFunction;
        if (!jsonMessage.bypass_auth && !parsedSqlObject.permissions_checked) {
            let permissionsCheck = checkASTPermissions(jsonMessage, parsedSqlObject);
            if (permissionsCheck && permissionsCheck.length > 0) {
                return callback(UNAUTHORIZED_RESPONSE, permissionsCheck);
            }
        }
        let statement = {
            statement: parsedSqlObject.ast.statements[0],
            hdb_user: jsonMessage.hdb_user,
        };
        switch (parsedSqlObject.variant) {
            case terms.VALID_SQL_OPS_ENUM.SELECT:
                sqlFunction = search_ts_1.search;
                statement = parsedSqlObject.ast.statements[0];
                break;
            case terms.VALID_SQL_OPS_ENUM.INSERT:
                //TODO add validator for insert, need to make sure columns are specified
                sqlFunction = convertInsert;
                break;
            case terms.VALID_SQL_OPS_ENUM.UPDATE:
                sqlFunction = cbUpdateUpdate;
                break;
            case terms.VALID_SQL_OPS_ENUM.DELETE:
                sqlFunction = cbDeleteTranslator;
                break;
            default:
                throw new Error(`unsupported SQL type ${parsedSqlObject.variant} in SQL: ${jsonMessage}`);
        }
        sqlFunction(statement, (err, data) => {
            if (err) {
                callback(err);
                return;
            }
            callback(null, data);
        });
    }
    catch (e) {
        return callback(e);
    }
}
function nullFunction(sql, callback) {
    harper_logger_ts_1.default.info(sql);
    callback('unknown sql statement');
}
function convertInsert({ statement, hdb_user }, callback) {
    let schemaTable = statement.into;
    let insertObject = {
        schema: schemaTable.databaseid,
        table: schemaTable.tableid,
        operation: 'insert',
        hdb_user,
    };
    let columns = statement.columns.map((column) => column.columnid);
    try {
        insertObject.records = createDataObjects(columns, statement.values);
    }
    catch (e) {
        return callback(e);
    }
    cbInsertInsert(insertObject, (err, res) => {
        if (err) {
            return callback(err);
        }
        try {
            // We do not want the API returning the new attributes property.
            delete res.new_attributes;
            delete res.txn_time;
        }
        catch (deleteErr) {
            harper_logger_ts_1.default.error(`Error delete new_attributes from insert response: ${deleteErr}`);
        }
        callback(null, res);
    });
}
function createDataObjects(columns, values) {
    try {
        return values.map((valueObjects) => {
            //compare number of values to number of columns, if no match throw error
            if (columns.length !== valueObjects.length) {
                throw 'number of values do not match number of columns in insert';
            }
            let record = {};
            //make sure none of the value entries have a columnid
            valueObjects.forEach((value, x) => {
                if (value.columnid) {
                    throw 'cannot use a column in insert value';
                }
                if ('value' in value) {
                    record[columns[x]] = value.value;
                }
                else {
                    record[columns[x]] = alasql.compile(`SELECT ${value.toString()} AS [${terms.FUNC_VAL}] FROM ?`);
                }
            });
            return record;
        });
    }
    catch (err) {
        harper_logger_ts_1.default.error(err);
        throw new Error(SQL_INSERT_ERROR_MSG);
    }
}
//# sourceMappingURL=index.js.map