// @ts-check

const _ = require("lodash");
const serverError = require("../../backend/serverError");
const runQuery = require("../../backend/db/runQuery");

/**
 * # Get Function FOr API
 *
 * @param {object} params
 * @param {string} params.query
 * @param {(string|number)[]} [params.queryValues]
 * @param {string} params.dbFullName
 * @param {string} [params.tableName]
 * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
 * @param {boolean} [params.useLocal]
 *
 * @returns {Promise<import("../../../types").GetReturn>}
 */
module.exports = async function apiGet({
    query,
    dbFullName,
    queryValues,
    tableName,
    dbSchema,
    useLocal,
}) {
    if (
        typeof query == "string" &&
        query.match(/^alter|^delete|information_schema|databases|^create/i)
    ) {
        return { success: false, msg: "Wrong Input." };
    }

    /**
     * Create new user folder and file
     *
     * @description Create new user folder and file
     */
    let results;

    try {
        let { result, error } = await runQuery({
            dbFullName: dbFullName,
            query: query,
            queryValuesArray: queryValues,
            readOnly: true,
            dbSchema,
            tableName,
            local: useLocal,
        });

        /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
        let tableSchema;

        if (dbSchema) {
            const targetTable = dbSchema.tables.find(
                (table) => table.tableName === tableName
            );

            if (targetTable) {
                const clonedTargetTable = _.cloneDeep(targetTable);
                delete clonedTargetTable.childTable;
                delete clonedTargetTable.childTableDbFullName;
                delete clonedTargetTable.childTableName;
                delete clonedTargetTable.childrenTables;
                delete clonedTargetTable.updateData;
                delete clonedTargetTable.tableNameOld;
                delete clonedTargetTable.indexes;
                tableSchema = clonedTargetTable;
            }
        }

        if (error) throw error;
        if (result.error) throw new Error(result.error);

        results = result;

        /** @type {import("../../../types").GetReturn} */
        const resObject = {
            success: true,
            payload: results,
            schema: tableName && tableSchema ? tableSchema : undefined,
        };

        return resObject;
    } catch (/** @type {any} */ error) {
        serverError({
            component: "/api/query/get/lines-85-94",
            message: error.message,
        });

        return { success: false, payload: null, error: error.message };
    }
};
