import fs from "fs";
import decrypt from "../dsql/decrypt";
import { CheckApiCredentialsFn } from "../../types";

/**
 * # Grap API Credentials
 */
const grabApiCred: CheckApiCredentialsFn = ({
    key,
    database,
    table,
    user_id,
    media,
}) => {
    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 = decrypt({ encryptedString: key });
        /** @type {import("../../types").ApiKeyObject} */
        const ApiObject: import("../../types").ApiKeyObject = JSON.parse(
            ApiJSON || ""
        );
        const isApiKeyValid = fs.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 = ApiObject.target_database
            ?.split(",")
            .includes(String(database));

        if (isDatabaseAllowed && !ApiObject.target_table) return ApiObject;
        if (isDatabaseAllowed && !table && ApiObject.target_table) return null;
        const isTableAllowed = ApiObject.target_table
            ?.split(",")
            .includes(String(table));
        if (isTableAllowed) return ApiObject;
        return null;
    } catch (/** @type {any} */ error: any) {
        console.log(`api-cred ERROR: ${error.message}`);
        return { error: `api-cred ERROR: ${error.message}` };
    }
};

export default grabApiCred;
