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

type Flash = {
    success?: string | null;
    error?: string | null;
};

function showFlash(flash: Flash | undefined): void {
    if (!flash) {
        return;
    }

    if (flash.success) {
        toast.success(flash.success);
    }

    if (flash.error) {
        toast.error(flash.error);
    }
}

export function useFlashToast(): void {
    router.on('flash', (event) => {
        showFlash(event.detail.flash as Flash);
    });

    router.on('success', (event) => {
        showFlash(event.detail.page.props.flash as Flash | undefined);
    });
}
