import fs from "fs";

import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
import createTable from "../utils/createTable";
import updateTable from "../utils/updateTable";
import dbHandler from "../utils/dbHandler";
import EJSON from "../../utils/ejson";
import { DSQL_DatabaseSchemaType } from "../../types";
import grabDirNames from "../../utils/backend/names/grab-dir-names";
import checkDbRecordCreateDbSchema from "./check-db-record";
import checkTableRecordCreateDbSchema from "./check-table-record";
import handleIndexescreateDbFromSchema from "./handle-indexes";

type Param = {
    userId?: number | string | null;
    targetDatabase?: string;
    dbSchemaData?: import("../../types").DSQL_DatabaseSchemaType[];
};

/**
 * # Create database from Schema Function
 * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
 */
export default async function createDbFromSchema({
    userId,
    targetDatabase,
    dbSchemaData,
}: Param): Promise<boolean> {
    const { userSchemaMainJSONFilePath, mainShemaJSONFilePath } = grabDirNames({
        userId,
    });

    const schemaPath = userSchemaMainJSONFilePath || mainShemaJSONFilePath;

    const dbSchema: DSQL_DatabaseSchemaType[] | undefined =
        dbSchemaData ||
        (EJSON.parse(fs.readFileSync(schemaPath, "utf8")) as
            | DSQL_DatabaseSchemaType[]
            | undefined);

    if (!dbSchema) {
        console.log("Schema Not Found!");
        return false;
    }

    for (let i = 0; i < dbSchema.length; i++) {
        const database: DSQL_DatabaseSchemaType = dbSchema[i];

        const { dbFullName, tables, dbSlug, childrenDatabases } = database;

        if (targetDatabase && dbFullName != targetDatabase) {
            continue;
        }

        const dbCheck: any = await noDatabaseDbHandler(
            `SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`
        );

        if (!dbCheck?.[0]?.dbFullName) {
            const newDatabase = await noDatabaseDbHandler(
                `CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`
            );
        }

        const allTables: any = await noDatabaseDbHandler(
            `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`
        );

        let recordedDbEntry = await checkDbRecordCreateDbSchema({
            dbSchema: database,
            userId,
        });

        for (let tb = 0; tb < allTables.length; tb++) {
            const { TABLE_NAME } = allTables[tb];

            /**
             * @description Check if TABLE_NAME is part of the tables contained
             * in the user schema JSON. If it's not, the table is either deleted
             * or the table name has been recently changed
             */
            if (
                !tables.filter((_table) => _table.tableName === TABLE_NAME)[0]
            ) {
                const oldTableFilteredArray = tables.filter(
                    (_table) =>
                        _table.tableNameOld &&
                        _table.tableNameOld === TABLE_NAME
                );

                /**
                 * @description Check if this table has been recently renamed. Rename
                 * table id true. Drop table if false
                 */
                if (oldTableFilteredArray && oldTableFilteredArray[0]) {
                    console.log("Renaming Table");
                    await varDatabaseDbHandler({
                        queryString: `RENAME TABLE \`${dbFullName}\`.\`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
                    });
                } else {
                    console.log(`Dropping Table from ${dbFullName}`);
                    await varDatabaseDbHandler({
                        queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
                    });

                    const deleteTableEntry = await dbHandler({
                        query: `DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
                        values: [userId, dbSlug, TABLE_NAME],
                    });
                }
            }
        }

        /**
         * @description Iterate through each table and perform table actions
         */
        for (let t = 0; t < tables.length; t++) {
            const table = tables[t];

            const { tableName, fields, indexes } = table;

            /**
             * @description Check if table exists
             * @type {any}
             */
            const tableCheck: any = await varDatabaseDbHandler({
                queryString: `
                    SELECT EXISTS (
                        SELECT
                        TABLE_NAME
                        FROM
                        information_schema.TABLES
                        WHERE
                        TABLE_SCHEMA = ? AND
                        TABLE_NAME = ?
                        ) AS tableExists`,
                queryValuesArray: [dbFullName, table.tableName],
            });

            ////////////////////////////////////////

            if (tableCheck && tableCheck[0]?.tableExists > 0) {
                /**
                 * @description Update table if table exists
                 */
                const updateExistingTable = await updateTable({
                    dbFullName: dbFullName,
                    tableName: tableName,
                    tableNameFull: table.tableFullName,
                    tableInfoArray: fields,
                    userId,
                    dbSchema,
                    tableIndexes: indexes,
                    tableIndex: t,
                    childDb: database.childDatabase || undefined,
                    recordedDbEntry,
                    tableSchema: table,
                });

                if (table.childrenTables && table.childrenTables[0]) {
                    for (let ch = 0; ch < table.childrenTables.length; ch++) {
                        const childTable = table.childrenTables[ch];

                        const updateExistingChildTable = await updateTable({
                            dbFullName: childTable.dbNameFull,
                            tableName: childTable.tableName,
                            tableNameFull: childTable.tableNameFull,
                            tableInfoArray: fields,
                            userId,
                            dbSchema,
                            tableIndexes: indexes,
                            clone: true,
                            childDb: database.childDatabase || undefined,
                            recordedDbEntry,
                            tableSchema: table,
                        });
                    }
                }
            } else {
                /**
                 * @description Create new Table if table doesnt exist
                 */
                const createNewTable = await createTable({
                    tableName: tableName,
                    tableInfoArray: fields,
                    dbFullName: dbFullName,
                    tableSchema: table,
                    recordedDbEntry,
                });

                /**
                 * Handle DATASQUIREL Table Indexes
                 * ===================================================
                 * @description Iterate through each datasquirel schema
                 * table index(if available), and perform operations
                 */
                if (indexes?.[0]) {
                    handleIndexescreateDbFromSchema({
                        dbFullName,
                        indexes,
                        tableName,
                    });
                }
            }

            const tableRecord = await checkTableRecordCreateDbSchema({
                dbFullName,
                dbSchema,
                tableSchema: table,
                dbRecord: recordedDbEntry,
                userId,
            });
        }

        /**
         * @description Check all children databases
         */
        if (childrenDatabases?.[0]) {
            for (let ch = 0; ch < childrenDatabases.length; ch++) {
                const childDb = childrenDatabases[ch];
                const { dbFullName } = childDb;

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

    return true;
}