import apiClient from "@/lib/api/client";
import type { ApiResponse } from "@/lib/api/types";
import type { NotificationOpenResult, NotificationsEnvelope } from "@/features/notification/notificationRecord";

/* Both of these hit the *same* endpoint. `unread_count` rides along at the
   envelope's top level, beside `data` rather than under `meta`, which is why
   the second wrapper exists at all — it reads the count off the same response
   the first one reads the list from. */
export const getNotifications = (): Promise<NotificationsEnvelope> =>
  apiClient.get("/notifications/").then((r) => r.data);

export const getUnreadNotificationsCount = (): Promise<NotificationsEnvelope> =>
  apiClient.get("/notifications/").then((r) => r.data);

/**
 * `NotificationController::markRead()` — one list **or** everything, never
 * both.
 *
 * The controller validates both keys as `nullable` and then rejects the two
 * combinations the validator cannot express: neither supplied is a 400
 * ("Either 'notification_ids' or 'mark_all' must be provided."), and *both*
 * supplied is also a 400. A union says that once.
 *
 * `is_read` is `['required', 'boolean']`, but `markRead()` merges `true` in
 * when the key is absent — so it is optional here and `false` is the only
 * value worth sending explicitly (that is the mark-as-*unread* path, which
 * returns a different `msg`).
 *
 * Not modelled, because no call site uses it: `normalizeNotificationIds()`
 * also accepts a bare `notification_id` or `id`, and wraps a scalar in an
 * array. Both of ours send `notification_ids` as an array already.
 */
export type MarkNotificationsReadBody = (
  | { notification_ids: number[]; mark_all?: never }
  | { mark_all: true; notification_ids?: never }
) & { is_read?: boolean };

/** `data: null` — the outcome is the `msg`. */
export const markNotificationsRead = (
  data: MarkNotificationsReadBody
): Promise<ApiResponse<null>> =>
  apiClient.post("/notifications/mark-read/", data).then((r) => r.data);

/** Marks the notification read and says whether its item still exists. */
export const openNotification = (
  id: string | number
): Promise<ApiResponse<NotificationOpenResult>> =>
  apiClient.post(`/notifications/${id}/open/`).then((r) => r.data);

/**
 * Deletes a single notification via the RESTful `DELETE /notifications/{id}/`.
 *
 * `data: null`. The path form is deliberate: the bulk endpoint takes its ids
 * in the request *body*, which many HTTP clients drop on a DELETE — the
 * backend's own comment says so.
 */
export const deleteNotifications = (
  id: string | number
): Promise<ApiResponse<null>> =>
  apiClient.delete(`/notifications/${id}/`).then((r) => r.data);
