// @ts-check

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

/**
 * # Post Function For API
 *
 * @param {object} params
 * @param {any} 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").PostReturn>}
 */
module.exports = async function apiPost({
    query,
    dbFullName,
    queryValues,
    tableName,
    dbSchema,
    useLocal,
}) {
    if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
        return { success: false, msg: "Wrong Input" };
    }

    if (
        typeof query === "object" &&
        query?.action?.match(/^create |^alter |^drop /i)
    ) {
        return { success: false, msg: "Wrong Input" };
    }

    /** @type {any} */
    let results;

    /**
     * Create new user folder and file
     *
     * @description Create new user folder and file
     */
    try {
        let { result, error } = await runQuery({
            dbFullName: dbFullName,
            query: query,
            dbSchema: dbSchema,
            queryValuesArray: queryValues,
            tableName,
            local: useLocal,
        });

        results = result;

        if (error) throw error;

        /** @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;
            }
        }

        return {
            success: true,
            payload: results,
            error: error,
            schema: tableName && tableSchema ? tableSchema : undefined,
        };

        ////////////////////////////////////////
    } catch (/** @type {any} */ error) {
        serverError({
            component: "/api/query/post/lines-132-142",
            message: error.message,
        });

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