'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.delete_ = void 0;
exports.deleteFilesBefore = deleteFilesBefore;
exports.deleteAuditLogsBefore = deleteAuditLogsBefore;
exports.deleteRecord = deleteRecord;
const bulkDeleteValidator_ts_1 = __importDefault(require("../validation/bulkDeleteValidator.js"));
const deleteValidator_ts_1 = __importDefault(require("../validation/deleteValidator.js"));
const commonUtils = __importStar(require("../utility/common_utils.js"));
const moment_1 = __importDefault(require("moment"));
const harper_logger_ts_1 = __importDefault(require("../utility/logging/harper_logger.js"));
const util_1 = require("util");
const terms = __importStar(require("../utility/hdbTerms.js"));
const globalSchema = __importStar(require("../utility/globalSchema.js"));
const pGlobalSchema = (0, util_1.promisify)(globalSchema.getTableSchema);
const harperBridge = require('./harperBridge/harperBridge').default;
const DataLayerObjects_ts_1 = require("./DataLayerObjects.js");
const hdbError_ts_1 = require("../utility/errors/hdbError.js");
const commonErrors_ts_1 = require("../utility/errors/commonErrors.js");
const DeleteAuditLogsBeforeResults_js_1 = __importDefault(require("./harperBridge/lmdbBridge/lmdbMethods/DeleteAuditLogsBeforeResults.js"));
const SUCCESS_MESSAGE = 'records successfully deleted';
// Callbackified functions
/**
 * Deletes files that have a system date before the date parameter.
 * Note this does not technically delete the values from the database.
 * This serves only to remove files for devices that have a small amount of disk space.
 *
 * @param deleteObj - the request passed from chooseOperation.
 */
async function deleteFilesBefore(deleteObj) {
    let validation = (0, bulkDeleteValidator_ts_1.default)(deleteObj, 'date');
    if (validation) {
        throw (0, hdbError_ts_1.handleHDBError)(validation, validation.message, commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST, undefined, undefined, true);
    }
    commonUtils.transformReq(deleteObj);
    let parsedDate = (0, moment_1.default)(deleteObj.date, moment_1.default.ISO_8601);
    if (!parsedDate.isValid()) {
        throw (0, hdbError_ts_1.handleHDBError)(new Error(), commonErrors_ts_1.HDB_ERROR_MSGS.INVALID_DATE, commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST, terms.LOG_LEVELS.ERROR, commonErrors_ts_1.HDB_ERROR_MSGS.INVALID_DATE, true);
    }
    let invalidSchemaTableMsg = commonUtils.checkSchemaTableExist(deleteObj.schema, deleteObj.table);
    if (invalidSchemaTableMsg) {
        throw (0, hdbError_ts_1.handleHDBError)(new Error(), invalidSchemaTableMsg, commonErrors_ts_1.HTTP_STATUS_CODES.NOT_FOUND, terms.LOG_LEVELS.ERROR, invalidSchemaTableMsg, true);
    }
    let results = await harperBridge.deleteRecordsBefore(deleteObj);
    await pGlobalSchema(deleteObj.schema, deleteObj.table);
    harper_logger_ts_1.default.info(`Finished deleting files before ${deleteObj.date}`);
    if (results && results.message) {
        return results.message;
    }
}
/**
 * Deletes audit logs which are older than a specific date
 *
 * @param {DeleteBeforeObject} deleteObj - the request passed from chooseOperation.
 *
 * @deprecated This has been deprecated in favor of deleteTransactionLogsBefore.
 */
async function deleteAuditLogsBefore(deleteObj) {
    let validation = (0, bulkDeleteValidator_ts_1.default)(deleteObj, 'timestamp');
    if (validation) {
        throw (0, hdbError_ts_1.handleHDBError)(validation, validation.message, commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST, undefined, undefined, true);
    }
    commonUtils.transformReq(deleteObj);
    if (isNaN(deleteObj.timestamp)) {
        throw (0, hdbError_ts_1.handleHDBError)(new Error(), commonErrors_ts_1.HDB_ERROR_MSGS.INVALID_VALUE('Timestamp'), commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST, terms.LOG_LEVELS.ERROR, commonErrors_ts_1.HDB_ERROR_MSGS.INVALID_VALUE('Timestamp'), true);
    }
    let invalidSchemaTableMsg = commonUtils.checkSchemaTableExist(deleteObj.schema, deleteObj.table);
    if (invalidSchemaTableMsg) {
        throw (0, hdbError_ts_1.handleHDBError)(new Error(), invalidSchemaTableMsg, commonErrors_ts_1.HTTP_STATUS_CODES.NOT_FOUND, terms.LOG_LEVELS.ERROR, invalidSchemaTableMsg, true);
    }
    const results = await harperBridge.deleteTransactionLogsBefore(deleteObj);
    await pGlobalSchema(deleteObj.schema, deleteObj.table);
    harper_logger_ts_1.default.info(`Finished deleting audit logs before ${deleteObj.timestamp}`);
    return new DeleteAuditLogsBeforeResults_js_1.default(results.start_timestamp, results.end_timestamp, results.transactions_deleted);
}
/**
 * Calls the harper bridge to delete records.
 * @param deleteObject
 * @returns {Promise<string>}
 */
async function deleteRecord(deleteObject) {
    if (deleteObject.ids)
        deleteObject.hash_values = deleteObject.ids;
    let validation = (0, deleteValidator_ts_1.default)(deleteObject);
    if (validation) {
        throw (0, hdbError_ts_1.handleHDBError)(validation, validation.message, commonErrors_ts_1.HTTP_STATUS_CODES.BAD_REQUEST, undefined, undefined, true);
    }
    commonUtils.transformReq(deleteObject);
    let invalidSchemaTableMsg = commonUtils.checkSchemaTableExist(deleteObject.schema, deleteObject.table);
    if (invalidSchemaTableMsg) {
        throw (0, hdbError_ts_1.handleHDBError)(new Error(), invalidSchemaTableMsg, commonErrors_ts_1.HTTP_STATUS_CODES.NOT_FOUND, terms.LOG_LEVELS.ERROR, invalidSchemaTableMsg, true);
    }
    try {
        await pGlobalSchema(deleteObject.schema, deleteObject.table);
        let deleteResultObject = await harperBridge.deleteRecords(deleteObject);
        if (commonUtils.isEmptyOrZeroLength(deleteResultObject.message)) {
            deleteResultObject.message = `${deleteResultObject.deleted_hashes.length} of ${deleteObject.hash_values.length} ${SUCCESS_MESSAGE}`;
        }
        return deleteResultObject;
    }
    catch (err) {
        if (err.message === terms.SEARCH_NOT_FOUND_MESSAGE) {
            let returnMsg = new DataLayerObjects_ts_1.DeleteResponseObject();
            returnMsg.message = terms.SEARCH_NOT_FOUND_MESSAGE;
            returnMsg.skipped_hashes = [deleteObject.hash_values.length];
            returnMsg.deleted_hashes = [];
            return returnMsg;
        }
        throw err;
    }
}
exports.delete_ = (0, util_1.callbackify)(deleteRecord);
//# sourceMappingURL=delete.js.map