// @ts-check

const serverError = require("./serverError");
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
const { default: setUserSchemaData } = require("./setUserSchemaData");
const createDbFromSchema = require("../../shell/createDbFromSchema");
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");

/**
 * # Add User Table to Database
 *
 * @param {object} params
 * @param {number | string} params.userId - user id
 * @param {string} params.database
 * @param {string[]} [params.newFields] - new fields to add to the users table
 * @param {Object<string, any>} [params.newPayload]
 *
 * @returns {Promise<any>} new user auth object payload
 */
module.exports = async function updateUsersTableSchema({
    userId,
    database,
    newFields,
    newPayload,
}) {
    try {
        const dbFullName = database;

        const userSchemaData = grabUserSchemaData({ userId });
        if (!userSchemaData) throw new Error("User schema data not found!");

        let targetDatabaseIndex = userSchemaData.findIndex(
            (db) => db.dbFullName === database
        );

        if (targetDatabaseIndex < 0) {
            throw new Error("Couldn't Find Target Database!");
        }

        let existingTableIndex = userSchemaData[
            targetDatabaseIndex
        ]?.tables.findIndex((table) => table.tableName === "users");

        const usersTable =
            userSchemaData[targetDatabaseIndex].tables[existingTableIndex];

        if (!usersTable?.fields?.[0]) throw new Error("Users Table Not Found!");

        const additionalFields = grabSchemaFieldsFromData({
            fields: newFields,
            data: newPayload,
        });

        const spliceStartIndex = usersTable.fields.findIndex(
            (field) => field.fieldName === "date_created"
        );
        const finalSpliceStartIndex =
            spliceStartIndex >= 0 ? spliceStartIndex : 0;

        usersTable.fields.splice(finalSpliceStartIndex, 0, ...additionalFields);

        setUserSchemaData({ schemaData: userSchemaData, userId });

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

        return `Done!`;
    } catch (/** @type {any} */ error) {
        console.log(`addUsersTableToDb.js ERROR: ${error.message}`);

        serverError({
            component: "addUsersTableToDb",
            message: error.message,
            user: { id: userId },
        });
        return error.message;
    }
};
