import {useMutation} from "@tanstack/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) {
                    const newGoogleAccounts = {...googleAccounts}
                    delete newGoogleAccounts[email];
                    newUserData.googleAccounts = newGoogleAccounts;
                }
            } else if (provider === "outlook") {
                let microsoftAccounts = profileData?.microsoftAccounts;
                if (microsoftAccounts) {
                    const newMicrosoftAccounts = {...microsoftAccounts}
                    delete microsoftAccounts[email];
                    newUserData.microsoftAccounts = newMicrosoftAccounts;
                }
            } else if (provider === "apple") {
                let appleAccounts = profileData?.appleAccounts;
                if (appleAccounts) {
                    const newAppleAccounts = {...appleAccounts}
                    delete newAppleAccounts[email];
                    newUserData.appleAccounts = newAppleAccounts;
                }
            }
            await updateUserData({newUserData});
        },
    })
}