'use client'
import {
  useServiceId
} from "./chunk-LDSJ6KYP.mjs";
import {
  m2mNotifications_v1
} from "./chunk-ISOF65DB.mjs";

// src/notification/NotificationProvider.tsx
import {
  createContext,
  useCallback,
  useContext
} from "react";
import { useAuthFetch } from "matsuri-hooks";
import { useMemo } from "react";
import { jsx } from "react/jsx-runtime";
var NotificationPermissionContext = createContext(void 0);
var NotificationsContext = createContext(void 0);
var NotificationsProvider = ({
  token,
  children
}) => {
  const serviceId = useServiceId();
  const { data: subscriptions, refetch: refetchSubscriptions } = useAuthFetch(token, m2mNotifications_v1.findMySubscriptions(), {});
  const checkPermission = useCallback(
    (notificationType) => {
      const subscription = subscriptions == null ? void 0 : subscriptions.find((item) => {
        return item.serviceId === serviceId && item.notificationType === notificationType && item.resourceSubscription.resourceSelectType === "any";
      });
      return subscription == null ? void 0 : subscription.status;
    },
    [serviceId, subscriptions]
  );
  const {
    data: notifications,
    error,
    refetch: refetchNotifications
  } = useAuthFetch(
    token,
    m2mNotifications_v1.findNotificationsByServiceId({ id: serviceId }),
    { swrConfig: { refreshInterval: 1e3 * 60 * 5 } }
  );
  if (error) {
    console.error(error);
  }
  const permissionContextState = useMemo(() => {
    return {
      checkPermission,
      refetch: refetchSubscriptions
    };
  }, [checkPermission, refetchSubscriptions]);
  const notificationsContextState = useMemo(() => {
    var _a, _b;
    return {
      notifications: (_a = notifications == null ? void 0 : notifications.data) != null ? _a : [],
      isAllRead: (_b = notifications == null ? void 0 : notifications.data.every((n) => n.status === "read")) != null ? _b : true,
      refetch: refetchNotifications
    };
  }, [refetchNotifications, notifications == null ? void 0 : notifications.data]);
  return /* @__PURE__ */ jsx(NotificationPermissionContext.Provider, { value: permissionContextState, children: /* @__PURE__ */ jsx(NotificationsContext.Provider, { value: notificationsContextState, children }) });
};
var useNotifications = () => {
  const ctx = useContext(NotificationsContext);
  if (!ctx) {
    throw new Error("NotificatoinProvider is not found");
  }
  return ctx;
};
var useNotificationPermission = () => {
  const ctx = useContext(NotificationPermissionContext);
  if (!ctx) {
    throw new Error("NotificatoinProvider is not found");
  }
  return ctx;
};

export {
  NotificationsProvider,
  useNotifications,
  useNotificationPermission
};
//# sourceMappingURL=chunk-VNCVFELM.mjs.map