// @ts-check

const handleSocialDb = require("../../social-login/handleSocialDb");
const githubLogin = require("../../social-login/githubLogin");
const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace");

/**
 * # Login with Github
 * @param {object} param
 * @param {string} [param.code]
 * @param {string} [param.clientId]
 * @param {string} [param.clientSecret]
 * @param {string} [param.database]
 * @param {string[]} [param.additionalFields]
 * @param {any} [param.res]
 * @param {string} [param.email]
 * @param {string | number} [param.userId]
 *
 * @returns {Promise<import("../../../../types").APIGoogleLoginFunctionReturn>}
 */
module.exports = async function apiGithubLogin({
    code,
    clientId,
    clientSecret,
    database,
    additionalFields,
    res,
    email,
    userId,
}) {
    if (!code || !clientId || !clientSecret || !database) {
        return {
            success: false,
            msg: "Missing query params",
        };
    }

    if (
        typeof code !== "string" ||
        typeof clientId !== "string" ||
        typeof clientSecret !== "string" ||
        typeof database !== "string"
    ) {
        return {
            success: false,
            msg: "Wrong Parameters",
        };
    }

    /**
     * Create new user folder and file
     *
     * @description Create new user folder and file
     */
    const gitHubUser = await githubLogin({
        code: code,
        clientId: clientId,
        clientSecret: clientSecret,
    });

    if (!gitHubUser) {
        return {
            success: false,
            msg: "No github user returned",
        };
    }

    const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
    const targetName = gitHubUser.name || gitHubUser.login;
    const nameArray = targetName?.match(/ /)
        ? targetName?.split(" ")
        : targetName?.match(/\-/)
        ? targetName?.split("-")
        : [targetName];

    const payload = {
        email: gitHubUser.email,
        first_name: camelJoinedtoCamelSpace(nameArray[0]),
        last_name: camelJoinedtoCamelSpace(nameArray[1]),
        social_id: socialId,
        social_platform: "github",
        image: gitHubUser.avatar_url,
        image_thumbnail: gitHubUser.avatar_url,
        username: "github-user-" + socialId,
    };

    const loggedInGithubUser = await handleSocialDb({
        database,
        email: gitHubUser.email,
        payload: payload,
        social_platform: "github",
        social_id: socialId,
        supEmail: email,
        additionalFields,
    });

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

    return { ...loggedInGithubUser };
};
