import https from "https";
import handleSocialDb from "../../social-login/handleSocialDb";
import EJSON from "../../../../utils/ejson";
import {
    APIGoogleLoginFunctionParams,
    APILoginFunctionReturn,
    GoogleOauth2User,
} from "../../../../types";

/**
 * # API google login
 */
export default async function apiGoogleLogin({
    token,
    database,
    additionalFields,
    additionalData,
}: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn> {
    try {
        const gUser: GoogleOauth2User | undefined = await new Promise(
            (resolve, reject) => {
                https
                    .request(
                        {
                            method: "GET",
                            hostname: "www.googleapis.com",
                            path: "/oauth2/v3/userinfo",
                            headers: {
                                Authorization: `Bearer ${token}`,
                            },
                        },
                        (res) => {
                            let data = "";
                            res.on("data", (chunk) => {
                                data += chunk;
                            });
                            res.on("end", () => {
                                resolve(EJSON.parse(data) as any);
                            });
                        }
                    )
                    .end();
            }
        );

        if (!gUser?.email_verified) throw new Error("No Google User.");

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

        if (!database || typeof database != "string" || database?.match(/ /)) {
            return {
                success: false,
                payload: undefined,
                msg: "Please provide a database slug(database name in lowercase with no spaces)",
            };
        }

        /**
         * Create new user folder and file
         *
         * @description Create new user folder and file
         */

        const { given_name, family_name, email, sub, picture } = gUser;

        let payloadObject: { [s: string]: any } = {
            email: email,
            first_name: given_name,
            last_name: family_name,
            social_id: sub,
            social_platform: "google",
            image: picture,
            image_thumbnail: picture,
            username: `google-user-${sub}`,
        };

        if (additionalData) {
            payloadObject = { ...payloadObject, ...additionalData };
        }

        const loggedInGoogleUser = await handleSocialDb({
            database,
            email: email || "",
            payload: payloadObject,
            social_platform: "google",
            social_id: sub,
            additionalFields,
        });

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

        return { ...loggedInGoogleUser };
    } catch (/** @type {any} */ error: any) {
        console.log(`api-google-login.ts ERROR: ${error.message}`);

        return {
            success: false,
            payload: undefined,
            msg: error.message,
        };
    }
}