import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
import dbHandler from "../utils/dbHandler";
import {
    DSQL_DatabaseSchemaType,
    DSQL_TableSchemaType,
    PostInsertReturn,
} from "../../types";
import {
    DSQL_DATASQUIREL_USER_DATABASE_TABLES,
    DSQL_DATASQUIREL_USER_DATABASES,
    DsqlTables,
} from "../../types/dsql";
import sqlGenerator from "../../functions/dsql/sql/sql-generator";
import numberfy from "../../utils/numberfy";
import addDbEntry from "../../functions/backend/db/addDbEntry";

type Param = {
    userId?: number | string | null;
    tableSchema?: DSQL_TableSchemaType;
    dbSchema: DSQL_DatabaseSchemaType[];
    dbRecord?: DSQL_DATASQUIREL_USER_DATABASES;
    dbFullName: string;
};

/**
 * # Create database from Schema Function
 * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
 */
export default async function checkTableRecordCreateDbSchema({
    userId,
    tableSchema,
    dbSchema,
    dbRecord,
    dbFullName,
}: Param): Promise<DSQL_DATASQUIREL_USER_DATABASE_TABLES | undefined> {
    if (!tableSchema) return undefined;

    try {
        const queryObj = sqlGenerator<DSQL_DATASQUIREL_USER_DATABASE_TABLES>({
            tableName: "user_database_tables" as (typeof DsqlTables)[number],
            genObject: {
                query: {
                    db_id: {
                        value: String(dbRecord?.id),
                    },
                    table_slug: {
                        value: tableSchema.tableName,
                    },
                    user_id: {
                        value: String(userId),
                    },
                },
            },
            dbFullName: "datasquirel",
        });

        let recordedTableEntryArray = userId
            ? await varDatabaseDbHandler({
                  queryString: queryObj?.string || "",
                  queryValuesArray: queryObj?.values,
              })
            : undefined;

        let recordedTableEntry:
            | DSQL_DATASQUIREL_USER_DATABASE_TABLES
            | undefined = recordedTableEntryArray?.[0];

        if (!recordedTableEntry?.id && userId) {
            const newTableInsertObject: DSQL_DATASQUIREL_USER_DATABASE_TABLES =
                {
                    user_id: numberfy(userId),
                    db_id: dbRecord?.id,
                    db_slug: dbRecord?.db_slug,
                    table_name: tableSchema.tableFullName,
                    table_slug: tableSchema.tableName,
                };

            if (tableSchema?.childTable && tableSchema.childTableName) {
                const parentDb = dbSchema.find(
                    (db) => db.dbFullName == tableSchema.childTableDbFullName
                );
                const parentDbTable = parentDb?.tables.find(
                    (tbl) => tbl.tableName == tableSchema.childTableName
                );
                if (parentDb && parentDbTable) {
                    newTableInsertObject["child_table"] = 1;
                    newTableInsertObject["child_table_parent_database"] =
                        parentDb.dbFullName;
                    newTableInsertObject["child_table_parent_table"] =
                        parentDbTable.tableName;
                }
            }

            const newTableRecordEntry = (await addDbEntry({
                data: newTableInsertObject,
                tableName: "user_database_tables",
                dbContext: "Master",
                forceLocal: true,
            })) as PostInsertReturn;

            if (newTableRecordEntry.insertId) {
                recordedTableEntryArray = await varDatabaseDbHandler({
                    queryString: queryObj?.string || "",
                    queryValuesArray: queryObj?.values,
                });

                recordedTableEntry = recordedTableEntryArray?.[0];
            }
        }

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