"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
/**
 * # Grap API Credentials
 */
const grabApiCred = ({ key, database, table, user_id, media, }) => {
    var _a, _b;
    if (!key)
        return null;
    if (!user_id)
        return null;
    try {
        const allowedKeysPath = process.env.DSQL_API_KEYS_PATH;
        if (!allowedKeysPath)
            throw new Error("process.env.DSQL_API_KEYS_PATH variable not found");
        const ApiJSON = (0, decrypt_1.default)({ encryptedString: key });
        /** @type {import("../../types").ApiKeyObject} */
        const ApiObject = JSON.parse(ApiJSON || "");
        const isApiKeyValid = fs_1.default.existsSync(`${allowedKeysPath}/${ApiObject.sign}`);
        if (String(ApiObject.user_id) !== String(user_id))
            return null;
        if (!isApiKeyValid)
            return null;
        if (!ApiObject.target_database)
            return ApiObject;
        if (media)
            return ApiObject;
        if (!database && ApiObject.target_database)
            return null;
        const isDatabaseAllowed = (_a = ApiObject.target_database) === null || _a === void 0 ? void 0 : _a.split(",").includes(String(database));
        if (isDatabaseAllowed && !ApiObject.target_table)
            return ApiObject;
        if (isDatabaseAllowed && !table && ApiObject.target_table)
            return null;
        const isTableAllowed = (_b = ApiObject.target_table) === null || _b === void 0 ? void 0 : _b.split(",").includes(String(table));
        if (isTableAllowed)
            return ApiObject;
        return null;
    }
    catch ( /** @type {any} */error) {
        console.log(`api-cred ERROR: ${error.message}`);
        return { error: `api-cred ERROR: ${error.message}` };
    }
};
exports.default = grabApiCred;