import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
import { DSQL_IndexSchemaType } from "../../types";

type Param = {
    tableName: string;
    dbFullName: string;
    indexes: DSQL_IndexSchemaType[];
};

/**
 * Handle DATASQUIREL Table Indexes
 * ===================================================
 * @description Iterate through each datasquirel schema
 * table index(if available), and perform operations
 */
export default async function handleIndexescreateDbFromSchema({
    dbFullName,
    tableName,
    indexes,
}: Param) {
    for (let g = 0; g < indexes.length; g++) {
        const { indexType, indexName, indexTableFields, alias } = indexes[g];

        if (!alias?.match(/./)) continue;

        /**
         * @description Check for existing Index in MYSQL db
         */
        try {
            /**
             * @type {import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
             * @description All indexes from MYSQL db
             */ // @ts-ignore
            const allExistingIndexes: import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[] =
                await varDatabaseDbHandler({
                    queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
                });

            const existingKeyInDb = allExistingIndexes.filter(
                (indexObject) => indexObject.Key_name === alias
            );
            if (!existingKeyInDb[0])
                throw new Error("This Index Does not Exist");
        } catch (error) {
            /**
             * @description Create new index if determined that it
             * doesn't exist in MYSQL db
             */
            await varDatabaseDbHandler({
                queryString: `CREATE${
                    indexType?.match(/fullText/i) ? " FULLTEXT" : ""
                } INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields
                    ?.map((nm) => nm.value)
                    .map((nm) => `\`${nm}\``)
                    .join(",")}) COMMENT 'schema_index'`,
            });
        }
    }
}
