import serverError from "./serverError";
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
import { default as grabUserSchemaData } from "./grabUserSchemaData";
import { default as setUserSchemaData } from "./setUserSchemaData";
import addDbEntry from "./db/addDbEntry";
import createDbFromSchema from "../../shell/createDbFromSchema";
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
import grabNewUsersTableSchema from "./grabNewUsersTableSchema";

type Param = {
    userId: number;
    database: string;
    payload?: { [s: string]: any };
};

/**
 * # Add User Table to Database
 */
export default async function addUsersTableToDb({
    userId,
    database,
    payload,
}: Param): Promise<any> {
    try {
        const dbFullName = database;

        const userPreset = grabNewUsersTableSchema({ payload });
        if (!userPreset) throw new Error("Couldn't Get User Preset!");

        const userSchemaData = grabUserSchemaData({ userId });
        if (!userSchemaData) throw new Error("User schema data not found!");

        let targetDatabase = userSchemaData.find(
            (db: any) => db.dbFullName === database
        );

        if (!targetDatabase) {
            throw new Error("Couldn't Find Target Database!");
        }

        let existingTableIndex = targetDatabase?.tables.findIndex(
            (table: any) => table.tableName === "users"
        );

        if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
            targetDatabase.tables[existingTableIndex] = userPreset;
        } else {
            targetDatabase.tables.push(userPreset);
        }

        setUserSchemaData({ schemaData: userSchemaData, userId });

        const targetDb: any[] | null = global.DSQL_USE_LOCAL
            ? await LOCAL_DB_HANDLER(
                  `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
                  [userId, database]
              )
            : await DB_HANDLER(
                  `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
                  [userId, database]
              );

        if (targetDb?.[0]) {
            const newTableEntry = await addDbEntry({
                dbFullName: "datasquirel",
                tableName: "user_database_tables",
                data: {
                    user_id: userId,
                    db_id: targetDb[0].id,
                    db_slug: targetDatabase.dbSlug,
                    table_name: "Users",
                    table_slug: "users",
                },
            });
        }

        const dbShellUpdate = await createDbFromSchema({
            userId,
            targetDatabase: dbFullName,
        });

        return `Done!`;
    } catch (/** @type {any} */ error: any) {
        console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);

        serverError({
            component: "addUsersTableToDb",
            message: error.message,
            user: { id: userId },
        });
        return error.message;
    }
}
