import { router } from '@inertiajs/vue3';
import { ref } from 'vue';
import { toast } from 'vue-sonner';

interface UseDestroyOptions {
    url: string;
    preserveScroll?: boolean;
    errorMessage?: string;
    onSuccess?: () => void;
    onError?: (errors: Record<string, string>) => string | void;
}

export function useDestroy({ url, preserveScroll = true, errorMessage, onSuccess, onError }: UseDestroyOptions) {
    const open = ref(false);
    const processing = ref(false);

    function destroy() {
        processing.value = true;

        router.delete(url, {
            preserveScroll,
            onSuccess: () => {
                open.value = false;
                onSuccess?.();
            },
            onError: (errors) => {
                if (onError) {
                    const result = onError(errors);
                    if (typeof result === 'string') {
                        toast.error(result);
                        return;
                    }
                }

                if (errorMessage) {
                    toast.error(errorMessage);
                }
            },
            onFinish: () => {
                processing.value = false;
            },
        });
    }

    return { open, processing, destroy };
}
