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

const hasExportNotifications = ref(false);
const hasMessageNotifications = ref(false);
let channel = null;

export function useRealtimeNotifications() {
  const { user } = useAuth();

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

    const channelName = `user.notifications.${current.id}`;

    channel = echo.private(channelName).listen(".ExportReady", (payload) => {
      if (payload?.type === "export-ready") {
        hasExportNotifications.value = true;
      }
    });
  });

  onBeforeUnmount(() => {
    // AppTopbar is effectively global; we intentionally keep the subscription
    // for the lifetime of the app. If this composable is reused elsewhere,
    // the cleanup below can be enabled.
    // if (channel) {
    //   echo.leave(channel.name);
    //   channel = null;
    // }
  });

  return {
    hasExportNotifications,
    hasMessageNotifications,
  };
}
