import handleSocialDb from "../../social-login/handleSocialDb";
import githubLogin from "../../social-login/githubLogin";
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
import { APILoginFunctionReturn } from "../../../../types";

type Param = {
    code?: string;
    clientId?: string;
    clientSecret?: string;
    database?: string;
    additionalFields?: string[];
    additionalData?: { [s: string]: string | number };
    email?: string;
};

/**
 * # API Login with Github
 */
export default async function apiGithubLogin({
    code,
    clientId,
    clientSecret,
    database,
    additionalFields,
    email,
    additionalData,
}: Param): Promise<APILoginFunctionReturn> {
    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];

    let 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,
    };

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

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

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

    return { ...loggedInGithubUser };
}
