import serverError from "./serverError";
import grabUserSchemaData from "./grabUserSchemaData";
import setUserSchemaData from "./setUserSchemaData";
import createDbFromSchema from "../../shell/createDbFromSchema";
import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData";

type Param = {
    userId: number | string;
    database: string;
    newFields?: string[];
    newPayload?: { [s: string]: any };
};

/**
 * # Add User Table to Database
 */
export default async function updateUsersTableSchema({
    userId,
    database,
    newFields,
    newPayload,
}: Param): Promise<any> {
    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 (error: any) {
        console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);

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