import { watch } from "vue";
import { usePage } from "@inertiajs/vue3";
import { toast } from "vue-sonner";

export function useFlashToast(): void {
  const page = usePage<{
    flash?: {
      success?: string;
      error?: string;
      toast?: { type: string; message: string };
    };
  }>();

  let lastKey: string | null = null;

  watch(
    () => {
      const f = page.props?.flash;
      return (
        f?.success ||
        f?.error ||
        (f?.toast ? `${f.toast.type}:${f.toast.message}` : null)
      );
    },
    (key) => {
      if (!key || key === lastKey) return;
      lastKey = key;

      const flash = page.props?.flash;
      if (flash?.success) toast.success(flash.success);
      if (flash?.error) toast.error(flash.error);
      if (flash?.toast) {
        const { type, message } = flash.toast;
        (toast as Record<string, (msg: string) => void>)[type]?.(message) ??
          toast(message);
      }
    },
    { immediate: true },
  );
}
