import { UserType } from "../../../types";
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
import handleNodemailer from "../../backend/handleNodemailer";
import serverError from "../../backend/serverError";
import hashPassword from "../../dsql/hashPassword";

/**
 * # Facebook Login
 */
export default async function facebookLogin({
    usertype,
    body,
}: {
    body: any;
    usertype: UserType;
}) {
    try {
        const foundUser = await DB_HANDLER(
            `SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`
        );

        if (foundUser && foundUser[0]) {
            return foundUser[0];
        }

        let socialHashedPassword = hashPassword({
            password: body.facebookUserId,
        });

        let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
            first_name,
            last_name,
            social_platform,
            social_name,
            email,
            image,
            image_thumbnail,
            password,
            verification_status,
            social_login,
            social_id,
            terms_agreement,
            date_created,
            date_code
            ) VALUES (
                '${body.facebookUserFirstName}',
                '${body.facebookUserLastName}',
                'facebook',
                'facebook_${
                    body.facebookUserEmail
                        ? body.facebookUserEmail.replace(/@.*/, "")
                        : body.facebookUserFirstName.toLowerCase()
                }',
                '${body.facebookUserEmail}',
                '${body.facebookUserImage}',
                '${body.facebookUserImage}',
                '${socialHashedPassword}',
                '1',
                '1',
                '${body.facebookUserId}',
                '1',
                '${Date()}',
                '${Date.now()}'
                )`);

        const newFoundUser = await DB_HANDLER(
            `SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
        );
    } catch (/** @type {any} */ error: any) {
        serverError({
            component: "functions/backend/facebookLogin",
            message: error.message,
        });
    }

    return {
        isFacebookAuthValid: false,
        newFoundUser: null,
    };
}
