import {useMutation} from "react-query";
import auth from "@react-native-firebase/auth";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
import {useSetUserData} from "./useSetUserData";
import {uuidv4} from "@firebase/util";
import * as Localization from "expo-localization";

export const useSignUp = () => {
    const {setRedirectOverride} = useAuthContext()
    const {mutateAsync: setUserData} = useSetUserData();

    return useMutation({
        mutationKey: ["signUp"],
        mutationFn: async ({
                               email,
                               password,
                               firstName,
                               lastName,
                           }: {
            email: string;
            password: string;
            firstName: string;
            lastName: string;
        }) => {
            setRedirectOverride(true)

            await auth()
                .createUserWithEmailAndPassword(email, password)
                .then(async (res) => {
                    try {
                        await setUserData({
                            newUserData: {
                                userType: ProfileType.PARENT,
                                firstName: firstName,
                                lastName: lastName,
                                familyId: uuidv4(),
                                timeZone: Localization.getCalendars()[0].timeZone,
                            },
                            customUser: res.user,
                        });
                    } catch (error) {
                        console.error(error);
                    }
                });
        },
    });
};