import { api } from "./client";

export const pushApi = {
  getVapidPublicKey(): Promise<{ publicKey: string | null }> {
    return api.get<{ publicKey: string | null }>("/push/vapid-public-key");
  },

  subscribe(
    subscription: ReturnType<PushSubscription["toJSON"]>,
    meta?: { userId?: string; companyId?: string; deviceLabel?: string },
  ): Promise<void> {
    return api.post<void>("/push/subscribe", { ...subscription, ...meta });
  },

  unsubscribe(endpoint: string): Promise<void> {
    // DELETE with body requires a manual fetch since api.delete() doesn't support body
    return fetch("/api/push/subscribe", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ endpoint }),
    }).then((res) => {
      if (!res.ok && res.status !== 204) {
        throw new Error(`Unsubscribe failed: ${res.status}`);
      }
    });
  },
};
