// @ts-check

import _ from "lodash";
import serverError from "../../backend/serverError";
import runQuery from "../../backend/db/runQuery";
import { DSQL_TableSchemaType, GetReturn } from "../../../types";

type Param = {
    query: string;
    queryValues?: (string | number)[];
    dbFullName: string;
    tableName?: string;
    dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
    useLocal?: boolean;
};

/**
 * # Get Function FOr API
 */
export default async function apiGet({
    query,
    dbFullName,
    queryValues,
    tableName,
    dbSchema,
    useLocal,
}: Param): Promise<import("../../../types").GetReturn> {
    if (
        typeof query == "string" &&
        query.match(/^alter|^delete|information_schema|databases|^create/i)
    ) {
        return { success: false, msg: "Wrong Input." };
    }

    let results;

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

        let tableSchema: DSQL_TableSchemaType | undefined;

        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;

        const resObject: GetReturn = {
            success: true,
            payload: results,
            schema: tableName && tableSchema ? tableSchema : undefined,
        };

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

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