import serverError from "./serverError";
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
import addDbEntry from "./db/addDbEntry";
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
import { DATASQUIREL_LoggedInUser } from "../../types";

type Param = {
    query: {
        invite: number;
        database_access: string;
        priviledge: string;
        email: string;
    };
    user: DATASQUIREL_LoggedInUser;
};

/**
 * Add Admin User on Login
 * ==============================================================================
 *
 * @description this function handles admin users that have been invited by another
 * admin user. This fires when the invited user has been logged in or a new account
 * has been created for the invited user
 */
export default async function addAdminUserOnLogin({
    query,
    user,
}: Param): Promise<any> {
    try {
        const finalDbHandler = global.DSQL_USE_LOCAL
            ? LOCAL_DB_HANDLER
            : DB_HANDLER;
        const { invite, database_access, priviledge, email } = query;

        const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
        const lastInviteTimeValues = [invite, email];

        const lastInviteTimeArray = await finalDbHandler(
            lastInviteTimeQuery,
            lastInviteTimeValues
        );

        if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
            throw new Error("No Invitation Found");
        }

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

        const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
        const invitingUserDbValues = [invite];

        const invitingUserDb = await finalDbHandler(
            invitingUserDbQuery,
            invitingUserDbValues
        );

        if (invitingUserDb?.[0]) {
            const existingUserUser = await finalDbHandler(
                `SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`,
                [invite, user.id, email]
            );

            if (existingUserUser?.[0]) {
                console.log("User already added");
            } else {
                addDbEntry({
                    dbFullName: "datasquirel",
                    tableName: "user_users",
                    data: {
                        user_id: invite,
                        invited_user_id: user.id,
                        database_access: database_access,
                        first_name: user.first_name,
                        last_name: user.last_name,
                        phone: user.phone,
                        email: user.email,
                        username: user.username,
                        user_type: "admin",
                        user_priviledge: priviledge,
                        image: user.image,
                        image_thumbnail: user.image_thumbnail,
                    },
                });

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

                const dbTableData = await finalDbHandler(
                    `SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
                    [invite, email]
                );

                const clearEntries = await finalDbHandler(
                    `DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`,
                    [invite, user.id]
                );

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

                if (dbTableData && dbTableData[0]) {
                    const dbTableEntries =
                        dbTableData[0].db_tables_data.split("|");

                    for (let i = 0; i < dbTableEntries.length; i++) {
                        const dbTableEntry = dbTableEntries[i];
                        const dbTableEntryArray = dbTableEntry.split("-");
                        const [db_slug, table_slug] = dbTableEntryArray;

                        const newEntry = await addDbEntry({
                            dbFullName: "datasquirel",
                            tableName: "delegated_user_tables",
                            data: {
                                delegated_user_id: user.id,
                                root_user_id: invite,
                                database: db_slug,
                                table: table_slug,
                                priviledge: priviledge,
                            },
                        });
                    }
                }
            }

            const inviteAccepted = await finalDbHandler(
                `UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`,
                [invite, email]
            );
        }
    } catch (error: any) {
        serverError({
            component: "addAdminUserOnLogin",
            message: error.message,
            user: user,
        });
    }
}
