import { onMounted, ref } from "vue";
import getEcho from "../services/realtime.js";
import { useAuth } from "./useAuth";

const hasExportNotifications = ref(false);
const hasMessageNotifications = ref(false);

let subscribed = false;

/** Private channel user.notifications.{id}; listen for `.ExportReady` (DataTable CSV). */
export function useRealtimeNotifications() {
  const { user } = useAuth();

  onMounted(() => {
    if (subscribed) return;
    const current = user.value;
    if (!current?.id) return;

    const echo = getEcho();
    if (!echo) return;

    const channelName = `user.notifications.${current.id}`;
    echo
      .private(channelName)
      .listen(".ExportReady", (payload) => {
        if (payload?.type === "export-ready") {
          hasExportNotifications.value = true;
        }
      });
    subscribed = true;
  });

  return {
    hasExportNotifications,
    hasMessageNotifications,
  };
}
