import checkIfIsMaster from "../../../utils/check-if-is-master";
import connDbHandler from "../../../utils/db/conn-db-handler";
import { DbContextsArray } from "./runQuery";

type Param = {
    dbContext?: (typeof DbContextsArray)[number];
    dbFullName: string;
    tableName: string;
    tableSchema?: import("../../../types").DSQL_TableSchemaType;
    identifierColumnName: string;
    identifierValue: string | number;
};

/**
 * # Delete DB Entry Function
 * @description
 */
export default async function deleteDbEntry({
    dbContext,
    dbFullName,
    tableName,
    identifierColumnName,
    identifierValue,
}: Param): Promise<object | null> {
    try {
        const isMaster = checkIfIsMaster({ dbContext, dbFullName });

        const DB_CONN = isMaster
            ? global.DSQL_DB_CONN
            : global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
        const DB_RO_CONN = isMaster
            ? global.DSQL_DB_CONN
            : global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;

        /**
         * Execution
         *
         * @description
         */
        const query = `DELETE FROM ${
            isMaster ? "" : `\`${dbFullName}\`.`
        }\`${tableName}\` WHERE \`${identifierColumnName}\`=?`;

        const deletedEntry = await connDbHandler(DB_CONN, query, [
            identifierValue,
        ]);

        /**
         * Return statement
         */
        return deletedEntry;
    } catch (error) {
        return null;
    }
}