import { useAuthContext } from "@/contexts/AuthContext";
import { useMutation } from "@tanstack/react-query";
import functions from '@react-native-firebase/functions';
import { Alert } from 'react-native';
import { useSignOut } from './useSignOut';

export const useDeleteFamily = () => {
    const { user } = useAuthContext();
    const signOut = useSignOut();

    return useMutation({
        mutationKey: ["deleteFamily"],
        mutationFn: async ({ familyId }: { familyId: string }) => {
            if (!user) {
                throw new Error('User must be logged in');
            }

            try {
                const deleteFamilyFunction = functions().httpsCallable('deleteFamily');
                const result = await deleteFamilyFunction({ familyId });
                
                if (result.data.success) {
                    await signOut.mutateAsync();
                }
                
                return result.data;
            } catch (error: any) {
                if (error.code === 'permission-denied') {
                    Alert.alert('Error', 'Only parents can delete families');
                } else if (error.code === 'unauthenticated') {
                    Alert.alert('Error', 'Please log in to perform this action');
                } else {
                    Alert.alert('Error', 'Failed to delete family. Please try again.');
                }
                throw error;
            }
        }
    });
};