/**
 * Web Push for category “new articles” notifications — same VAPID/SW as article/pickup push.
 */

export {
  PUSH_SUBSCRIPTIONS_CHANGED_EVENT,
  emitPushSubscriptionsChanged,
  fetchPushConfiguration,
  registerPushServiceWorker,
  ensurePushSubscription,
  isPushApiSupported,
  parseSubscribedStatus,
  parseSuccess,
} from "./articlePush.js";

/**
 * @param {number} kKategorie
 * @param {string} endpoint
 */
export async function categoryPushStatus(kKategorie, endpoint) {
  const res = await fetch("/api/category/push/status", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ kKategorie, endpoint }),
  });
  const data = await res.json().catch(() => ({}));
  return { ...data, httpOk: res.ok };
}

/**
 * @param {number} kKategorie
 * @param {PushSubscription} subscription
 */
export async function categoryPushSubscribe(kKategorie, subscription) {
  const subJson = subscription.toJSON();
  const res = await fetch("/api/category/push/subscribe", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      kKategorie,
      subscription: subJson,
    }),
  });
  const data = await res.json().catch(() => ({}));
  return { ...data, httpOk: res.ok };
}

/** POST /api/category/push/unsubscribe — body is always `{ endpoint, kKategorie }` (scoped row only). */
export async function categoryPushUnsubscribe(endpoint, kKategorie) {
  const parsed =
    kKategorie != null && kKategorie !== ""
      ? typeof kKategorie === "number"
        ? kKategorie
        : parseInt(String(kKategorie), 10)
      : NaN;
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return { success: false, httpOk: false, error: "missing_kKategorie" };
  }
  const body = { endpoint, kKategorie: parsed };
  const res = await fetch("/api/category/push/unsubscribe", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  const data = await res.json().catch(() => ({}));
  return { ...data, httpOk: res.ok };
}
