import _ from "lodash";
import serverError from "../../backend/serverError";
import runQuery, { DbContextsArray } from "../../backend/db/runQuery";
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";

type Param = {
    query: any;
    queryValues?: (string | number)[];
    dbFullName: string;
    tableName?: string;
    dbSchema?: DSQL_DatabaseSchemaType;
    dbContext?: (typeof DbContextsArray)[number];
    forceLocal?: boolean;
};

/**
 * # Post Function For API
 */
export default async function apiPost({
    query,
    dbFullName,
    queryValues,
    tableName,
    dbSchema,
    dbContext,
    forceLocal,
}: Param): Promise<PostReturn> {
    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" };
    }

    let results: any;

    /**
     * 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,
            dbContext,
            forceLocal,
        });

        results = result;

        if (error) throw error;

        let tableSchema:
            | import("../../../types").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;
            }
        }

        return {
            success: true,
            payload: results,
            error: error,
            schema: tableName && tableSchema ? tableSchema : undefined,
        };
    } catch (error: any) {
        serverError({
            component: "/api/query/post/lines-132-142",
            message: error.message,
        });

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