import {useMutation} from "react-query";
import {UserProfile} from "@firebase/auth";
import {useAuthContext} from "@/contexts/AuthContext";
import {useUpdateUserData} from "@/hooks/firebase/useUpdateUserData";

export const useClearTokens = () => {
    const {profileData} = useAuthContext();
    const {mutateAsync: updateUserData} = useUpdateUserData();

    return useMutation({
        mutationKey: ["clearTokens"],
        mutationFn: async ({provider, email}: {
            provider: "google" | "outlook" | "apple",
            email: string
        }) => {
            const newUserData: Partial<UserProfile> = {};
            if (provider === "google") {
                let googleAccounts = profileData?.googleAccounts;
                if (googleAccounts) {
                    googleAccounts[email] = null;
                    newUserData.googleAccounts = googleAccounts;
                }
            } else if (provider === "outlook") {
                let microsoftAccounts = profileData?.microsoftAccounts;
                if (microsoftAccounts) {
                    microsoftAccounts[email] = null;
                    newUserData.microsoftAccounts = microsoftAccounts;
                }
            } else if (provider === "apple") {
                let appleAccounts = profileData?.appleAccounts;
                if (appleAccounts) {
                    appleAccounts[email] = null;
                    newUserData.appleAccounts = appleAccounts;
                }
            }
            await updateUserData({newUserData});
        },
    })
}