"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = createTable;
const varDatabaseDbHandler_1 = __importDefault(require("./varDatabaseDbHandler"));
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
const supplementTable_1 = __importDefault(require("./supplementTable"));
const dbHandler_1 = __importDefault(require("./dbHandler"));
/**
 * # Create Table Functions
 */
function createTable(_a) {
    return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableInfoArray, tableSchema, recordedDbEntry, }) {
        /**
         * Format tableInfoArray
         *
         * @description Format tableInfoArray
         */
        const finalTable = (0, supplementTable_1.default)({ tableInfoArray: tableInfoArray });
        /**
         * Grab Schema
         *
         * @description Grab Schema
         */
        const createTableQueryArray = [];
        createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${dbFullName}\`.\`${tableName}\` (`);
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        try {
            if (!recordedDbEntry) {
                throw new Error("Recorded Db entry not found!");
            }
            const existingTable = yield (0, varDatabaseDbHandler_1.default)({
                queryString: `SELECT * FROM datasquirel.user_database_tables WHERE db_id = ? AND table_slug = ?`,
                queryValuesArray: [recordedDbEntry.id, tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName],
            });
            /** @type {import("../../types").MYSQL_user_database_tables_table_def} */
            const table = existingTable === null || existingTable === void 0 ? void 0 : existingTable[0];
            if (!(table === null || table === void 0 ? void 0 : table.id)) {
                const newTableEntry = yield (0, dbHandler_1.default)({
                    query: `INSERT INTO datasquirel.user_database_tables SET ?`,
                    values: {
                        user_id: recordedDbEntry.user_id,
                        db_id: recordedDbEntry.id,
                        db_slug: recordedDbEntry.db_slug,
                        table_name: tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableFullName,
                        table_slug: tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName,
                        child_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) ? "1" : null,
                        child_table_parent_database: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableDbFullName) || null,
                        child_table_parent_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableName) || null,
                        date_created: Date(),
                        date_created_code: Date.now(),
                        date_updated: Date(),
                        date_updated_code: Date.now(),
                    },
                });
            }
        }
        catch (error) { }
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
        let primaryKeySet = false;
        /** @type {import("../../types").DSQL_FieldSchemaType[]} */
        let foreignKeys = [];
        ////////////////////////////////////////
        for (let i = 0; i < finalTable.length; i++) {
            const column = finalTable[i];
            const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField, onUpdate, onUpdateLiteral, onDelete, onDeleteLiteral, defaultField, encrypted, json, newTempField, notNullValue, originName, plainText, pattern, patternFlags, richText, } = column;
            if (foreignKey) {
                foreignKeys.push(Object.assign({}, column));
            }
            let { fieldEntryText, newPrimaryKeySet } = (0, generateColumnDescription_1.default)({
                columnData: column,
                primaryKeySet: primaryKeySet,
            });
            primaryKeySet = newPrimaryKeySet;
            ////////////////////////////////////////
            const comma = (() => {
                if (foreignKeys[0])
                    return ",";
                if (i === finalTable.length - 1)
                    return "";
                return ",";
            })();
            createTableQueryArray.push("    " + fieldEntryText + comma);
            ////////////////////////////////////////
        }
        if (foreignKeys[0]) {
            foreignKeys.forEach((foreighKey, index, array) => {
                var _a, _b, _c, _d, _e;
                const fieldName = foreighKey.fieldName;
                const destinationTableName = (_a = foreighKey.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableName;
                const destinationTableColumnName = (_b = foreighKey.foreignKey) === null || _b === void 0 ? void 0 : _b.destinationTableColumnName;
                const cascadeDelete = (_c = foreighKey.foreignKey) === null || _c === void 0 ? void 0 : _c.cascadeDelete;
                const cascadeUpdate = (_d = foreighKey.foreignKey) === null || _d === void 0 ? void 0 : _d.cascadeUpdate;
                const foreignKeyName = (_e = foreighKey.foreignKey) === null || _e === void 0 ? void 0 : _e.foreignKeyName;
                const comma = (() => {
                    if (index === foreignKeys.length - 1)
                        return "";
                    return ",";
                })();
                createTableQueryArray.push(`    CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`);
            });
        }
        ////////////////////////////////////////
        createTableQueryArray.push(`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`);
        const createTableQuery = createTableQueryArray.join("\n");
        ////////////////////////////////////////
        const newTable = yield (0, varDatabaseDbHandler_1.default)({
            queryString: createTableQuery,
        });
        return newTable;
    });
}