import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
import { DSQL_DatabaseSchemaType, PostInsertReturn } from "../../types";
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
import numberfy from "../../utils/numberfy";
import addDbEntry from "../../functions/backend/db/addDbEntry";

type Param = {
    userId?: number | string | null;
    dbSchema: DSQL_DatabaseSchemaType;
};

/**
 * # Create database from Schema Function
 * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
 */
export default async function checkDbRecordCreateDbSchema({
    userId,
    dbSchema,
}: Param): Promise<DSQL_DATASQUIREL_USER_DATABASES | undefined> {
    try {
        const {
            dbFullName,
            dbName,
            dbSlug,
            dbDescription,
            dbImage,
            childDatabase,
            childDatabaseDbFullName,
        } = dbSchema;

        let recordedDbEntryArray = userId
            ? await varDatabaseDbHandler({
                  queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
                  queryValuesArray: [dbFullName],
              })
            : undefined;

        let recordedDbEntry: DSQL_DATASQUIREL_USER_DATABASES | undefined =
            recordedDbEntryArray?.[0];

        if (!recordedDbEntry?.id && userId) {
            const newDbEntryObj: DSQL_DATASQUIREL_USER_DATABASES = {
                user_id: numberfy(userId),
                db_name: dbName,
                db_slug: dbSlug,
                db_full_name: dbFullName,
                db_description: dbDescription,
                db_image: dbImage,
                active_clone: childDatabase ? 1 : undefined,
                active_clone_parent_db: childDatabaseDbFullName,
            };

            const newDbEntry = (await addDbEntry({
                data: newDbEntryObj,
                tableName: "user_databases",
                forceLocal: true,
            })) as PostInsertReturn;

            if (newDbEntry.insertId) {
                recordedDbEntryArray = await varDatabaseDbHandler({
                    queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
                    queryValuesArray: [dbFullName],
                });
                recordedDbEntry = recordedDbEntryArray?.[0];
            }
        }

        return recordedDbEntry;
    } catch (error) {
        return undefined;
    }
}
