import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
import httpsRequest from "../../backend/httpsRequest";

export interface GithubUserPayload {
    login: string;
    id: number;
    node_id: string;
    avatar_url: string;
    gravatar_id: string;
    url: string;
    html_url: string;
    followers_url: string;
    following_url: string;
    gists_url: string;
    starred_url: string;
    subscriptions_url: string;
    organizations_url: string;
    repos_url: string;
    received_events_url: string;
    type: string;
    site_admin: boolean;
    name: string;
    company: string;
    blog: string;
    location: string;
    email: string;
    hireable: string;
    bio: string;
    twitter_username: string;
    public_repos: number;
    public_gists: number;
    followers: number;
    following: number;
    created_at: string;
    updated_at: string;
}

type Param = {
    code: string;
    clientId: string;
    clientSecret: string;
};

/**
 * # Login/signup a github user
 */
export default async function githubLogin({
    code,
    clientId,
    clientSecret,
}: Param): Promise<GithubUserPayload | null | undefined> {
    let gitHubUser: GithubUserPayload | undefined;

    try {
        const response = await httpsRequest({
            method: "POST",
            hostname: "github.com",
            path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
            headers: {
                Accept: "application/json",
                "User-Agent": "*",
            },
            scheme: "https",
        });

        const accessTokenObject = JSON.parse(response as string);

        if (!accessTokenObject?.access_token) {
            return gitHubUser;
        }

        const userDataResponse = await httpsRequest({
            method: "GET",
            hostname: "api.github.com",
            path: "/user",
            headers: {
                Authorization: `Bearer ${accessTokenObject.access_token}`,
                "User-Agent": "*",
            },
            scheme: "https",
        });

        gitHubUser = JSON.parse(userDataResponse as string);

        if (!gitHubUser?.email && gitHubUser) {
            const existingGithubUser = await DB_HANDLER(
                `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`
            );

            if (existingGithubUser && existingGithubUser[0]) {
                gitHubUser.email = existingGithubUser[0].email;
            }
        }
    } catch (/** @type {any} */ error: any) {
        console.log(
            "ERROR in githubLogin.ts backend function =>",
            error.message
        );
    }

    return gitHubUser;
}
