"use client"
import {getUserInfo,createUser} from '@/app/util/db'
import {getAuth,signInWithPopup, GoogleAuthProvider} from "firebase/auth";
import { initializeApp } from "firebase/app";
import Config from '../Firebase/Config'
const app = initializeApp(Config);
const auth = getAuth(app)
const provider = new GoogleAuthProvider();

const Google = () => {
    return new Promise(async(resolve, reject) => {
        signInWithPopup(auth, provider).then(async(result) => {
            const credential = GoogleAuthProvider.credentialFromResult(result);
            const token = credential.accessToken;
            const user = result.user;
            console.log(credential)
            console.log(token)
            await getUserInfo(user.uid)
            .then(async res=>{
                if(res.length == 0) {
                    await createUser(user.uid, user.displayName, "Google",user.email).catch(err=>{
                        console.log(err)
                    })
                }
               resolve(user.uid)
            }).catch(err=>{
                console.log(err)
                reject(err.message)
            })

        }).catch((error) => {
            // Handle Errors here.
            // const errorCode = error.code;
            // const errorMessage = error.message;
            // // The email of the user's accoaunt used.
            // const email = error.customData.email;
            // // The AuthCredential type that was used.
            // const credential = GoogleAuthProvider.credentialFromError(error);
            console.log(error)
            reject(error.message.replace('Firebase: ',''))
        });

    })
}

export default Google