// @ts-check

const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
const { ServerResponse } = require("http");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
const encrypt = require("../../dsql/encrypt");
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");

/**
 * Function to login social user
 * ==============================================================================
 * @description This function logs in the user after 'handleSocialDb' function finishes
 * the user creation or confirmation process
 *
 * @async
 *
 * @param {object} params - function parameters inside an object
 * @param {{
 *  first_name: string,
 *  last_name: string,
 *  email: string,
 *  social_id: string|number,
 * }} params.user - user object
 * @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
 * @param {any} [params.invitation] - A query object if user was invited
 * @param {string} [params.database] - Target Database
 * @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
 * @param {boolean} [params.useLocal]
 *
 * @returns {Promise<import("../../../types").APILoginFunctionReturn>}
 */
async function loginSocialUser({
    user,
    social_platform,
    invitation,
    database,
    additionalFields,
    useLocal,
}) {
    const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
    const foundUserValues = [user.email, user.social_id, social_platform];

    const foundUser = await varDatabaseDbHandler({
        database: database ? database : "datasquirel",
        queryString: foundUserQuery,
        queryValuesArray: foundUserValues,
        useLocal,
    });

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

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

    /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
    let userPayload = {
        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,
            useLocal,
        });
    }

    /** @type {import("../../../types").APILoginFunctionReturn} */
    let result = {
        success: true,
        payload: userPayload,
        csrf: csrfKey,
    };

    return result;
}

module.exports = loginSocialUser;
