import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
import {
    APILoginFunctionReturn,
    DATASQUIREL_LoggedInUser,
} from "../../../types";

type Param = {
    user: {
        first_name: string;
        last_name: string;
        email: string;
        social_id: string | number;
    };
    social_platform: string;
    invitation?: any;
    database?: string;
    additionalFields?: string[];
    debug?: boolean;
};

/**
 * Function to login social user
 * ==============================================================================
 * @description This function logs in the user after 'handleSocialDb' function finishes
 * the user creation or confirmation process
 */
export default async function loginSocialUser({
    user,
    social_platform,
    invitation,
    database,
    additionalFields,
    debug,
}: Param): Promise<APILoginFunctionReturn> {
    const finalDbName = database ? database : "datasquirel";
    const dbAppend = database ? `\`${finalDbName}\`.` : "";

    const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=? AND social_id=? AND social_platform=?`;
    const foundUserValues = [user.email, user.social_id, social_platform];

    const foundUser = await varDatabaseDbHandler({
        database: finalDbName,
        queryString: foundUserQuery,
        queryValuesArray: foundUserValues,
        debug,
    });

    if (!foundUser?.[0])
        return {
            success: false,
            payload: null,
        };

    let csrfKey =
        Math.random().toString(36).substring(2) +
        "-" +
        Math.random().toString(36).substring(2);

    let userPayload: DATASQUIREL_LoggedInUser = {
        id: foundUser[0].id,
        first_name: foundUser[0].first_name,
        last_name: foundUser[0].last_name,
        username: foundUser[0].username,
        user_type: foundUser[0].user_type,
        email: foundUser[0].email,
        social_id: foundUser[0].social_id,
        image: foundUser[0].image,
        image_thumbnail: foundUser[0].image_thumbnail,
        verification_status: foundUser[0].verification_status,
        social_login: foundUser[0].social_login,
        social_platform: foundUser[0].social_platform,
        csrf_k: csrfKey,
        logged_in_status: true,
        date: Date.now(),
    };

    if (additionalFields?.[0]) {
        additionalFields.forEach((key) => {
            userPayload[key] = foundUser[0][key];
        });
    }

    if (invitation && (!database || database?.match(/^datasquirel$/))) {
        addAdminUserOnLogin({
            query: invitation,
            user: userPayload,
        });
    }

    let result: APILoginFunctionReturn = {
        success: true,
        payload: userPayload,
        csrf: csrfKey,
    };

    return result;
}
