// @ts-check

const https = require("https");
const handleSocialDb = require("../../social-login/handleSocialDb");
const EJSON = require("../../../../utils/ejson");

/** @type {import("../../../../types").APIGoogleLoginFunction} */
module.exports = async function apiGoogleLogin({
    token,
    database,
    additionalFields,
}) {
    try {
        /** @type {import("../../../../types").GoogleOauth2User | undefined} */
        const gUser = 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(/** @type {any} */ (EJSON.parse(data)));
                        });
                    }
                )
                .end();
        });

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

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

        if (!database || typeof database != "string" || database?.match(/ /)) {
            return {
                success: false,
                user: 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;

        /** @type {Object<string, any>} */
        const payloadObject = {
            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}`,
        };

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

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

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

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