'use client'
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/notification/index.ts
var notification_exports = {};
__export(notification_exports, {
  NotificationsProvider: () => NotificationsProvider,
  ServiceIdProvider: () => ServiceIdProvider,
  requestSubscribe: () => requestSubscribe,
  requestUnSubscribe: () => requestUnSubscribe,
  requestUpdateNotificationStatusToRead: () => requestUpdateNotificationStatusToRead,
  useNotificationPermission: () => useNotificationPermission,
  useNotifications: () => useNotifications,
  useServiceId: () => useServiceId
});
module.exports = __toCommonJS(notification_exports);

// src/notification/api.ts
var import_matsuri_hooks = require("matsuri-hooks");

// src/endpoints/m2m-notifications.v1.ts
var root = () => {
  let __root = "";
  if (globalThis.M2M_COMPONENTS_ENV === "local") {
    __root = "";
  }
  if (globalThis.M2M_COMPONENTS_ENV === "localDev") {
    __root = "";
  }
  if (globalThis.M2M_COMPONENTS_ENV === "development") {
    __root = "https://api-notifications.dev.m2msystems.cloud";
  }
  if (globalThis.M2M_COMPONENTS_ENV === "production") {
    __root = "https://api-notifications.m2msystems.cloud";
  }
  return __root;
};
var healthCheck = () => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`health_check`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};
var registerNotification = () => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`notifications`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};
var findNotificationsByServiceId = ({ id }) => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`notifications/by_service_id/${id}`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};
var updateNotificationStatus = ({ id }) => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`notifications/${id}`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};
var saveSubscription = () => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`subscriptions`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};
var findMySubscriptions = () => {
  const __root = root();
  const __queries = Object.entries({}).filter(([_, value]) => {
    return value !== void 0;
  }).map(([key, value]) => {
    return `${key}=${value}`;
  }).join("&");
  const __path = `${__root}/${`subscriptions`}`;
  return __queries ? `${__path}?${__queries}` : __path;
};
var m2mNotifications_v1 = {
  healthCheck,
  registerNotification,
  findNotificationsByServiceId,
  updateNotificationStatus,
  saveSubscription,
  findMySubscriptions
};

// src/notification/api.ts
var requestUpdateNotificationStatusToRead = async (token, id) => {
  await (0, import_matsuri_hooks.fetcher)(
    m2mNotifications_v1.updateNotificationStatus({
      id
    }),
    {
      method: "PUT",
      token,
      body: JSON.stringify({ status: "read" })
    }
  );
};
var requestSubscribe = async (token, serviceId, input) => {
  const { error } = await (0, import_matsuri_hooks.fetcher)(m2mNotifications_v1.saveSubscription(), {
    method: "POST",
    token,
    body: JSON.stringify({
      ...input,
      serviceId,
      status: "subscribed"
    })
  });
  if (error) {
    console.error(error);
  }
};
var requestUnSubscribe = async (token, serviceId, input) => {
  const { error } = await (0, import_matsuri_hooks.fetcher)(m2mNotifications_v1.saveSubscription(), {
    method: "POST",
    token,
    body: JSON.stringify({
      ...input,
      serviceId,
      status: "denied"
    })
  });
  if (error) {
    console.error(error);
  }
};

// src/notification/ServiceIdProvider.tsx
var import_react = __toESM(require("react"));
var import_jsx_runtime = require("react/jsx-runtime");
var ServiceIdContext = (0, import_react.createContext)(
  void 0
);
var ServiceIdProvider = ({
  serviceId,
  children
}) => {
  const state = (0, import_react.useMemo)(() => ({ serviceId }), [serviceId]);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ServiceIdContext.Provider, { value: state, children });
};
var useServiceId = () => {
  const context = import_react.default.useContext(ServiceIdContext);
  if (context === void 0) {
    throw new Error("useServiceId must be used within a ServiceIdProvider");
  }
  return context.serviceId;
};

// src/notification/NotificationProvider.tsx
var import_react2 = require("react");
var import_matsuri_hooks2 = require("matsuri-hooks");
var import_react3 = require("react");
var import_jsx_runtime2 = require("react/jsx-runtime");
var NotificationPermissionContext = (0, import_react2.createContext)(void 0);
var NotificationsContext = (0, import_react2.createContext)(void 0);
var NotificationsProvider = ({
  token,
  children
}) => {
  const serviceId = useServiceId();
  const { data: subscriptions, refetch: refetchSubscriptions } = (0, import_matsuri_hooks2.useAuthFetch)(token, m2mNotifications_v1.findMySubscriptions(), {});
  const checkPermission = (0, import_react2.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
  } = (0, import_matsuri_hooks2.useAuthFetch)(
    token,
    m2mNotifications_v1.findNotificationsByServiceId({ id: serviceId }),
    { swrConfig: { refreshInterval: 1e3 * 60 * 5 } }
  );
  if (error) {
    console.error(error);
  }
  const permissionContextState = (0, import_react3.useMemo)(() => {
    return {
      checkPermission,
      refetch: refetchSubscriptions
    };
  }, [checkPermission, refetchSubscriptions]);
  const notificationsContextState = (0, import_react3.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__ */ (0, import_jsx_runtime2.jsx)(NotificationPermissionContext.Provider, { value: permissionContextState, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(NotificationsContext.Provider, { value: notificationsContextState, children }) });
};
var useNotifications = () => {
  const ctx = (0, import_react2.useContext)(NotificationsContext);
  if (!ctx) {
    throw new Error("NotificatoinProvider is not found");
  }
  return ctx;
};
var useNotificationPermission = () => {
  const ctx = (0, import_react2.useContext)(NotificationPermissionContext);
  if (!ctx) {
    throw new Error("NotificatoinProvider is not found");
  }
  return ctx;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  NotificationsProvider,
  ServiceIdProvider,
  requestSubscribe,
  requestUnSubscribe,
  requestUpdateNotificationStatusToRead,
  useNotificationPermission,
  useNotifications,
  useServiceId
});
//# sourceMappingURL=index.js.map