export type NotificationDeliveryStatus = "unread" | "read" | "archived";
export type NotificationSurface = "hub" | "engine" | "operational-core";

export interface NotificationDelivery {
  id: string;
  eventId: string;
  eventType?: string | null;
  sourceService?: string | null;
  recipientUserId?: string | null;
  recipientEmail?: string | null;
  surface: NotificationSurface;
  title: string;
  body: string;
  meta?: Record<string, unknown>;
  status: NotificationDeliveryStatus;
  unread?: boolean;
  actionable?: boolean;
  actionType?: string | null;
  actionUrl?: string | null;
  entityType?: string | null;
  entityId?: string | null;
  eventPayload?: Record<string, unknown>;
  createdAt: string;
  updatedAt?: string | null;
  readAt?: string | null;
}

export async function fetchNotifications(surface: NotificationSurface) {
  const response = await fetch(`/api/notifications?surface=${encodeURIComponent(surface)}`, {
    headers: { Accept: "application/json" },
  });
  if (!response.ok) throw new Error(`notifications_failed_${response.status}`);
  const payload = await response.json();
  return Array.isArray(payload?.deliveries) ? payload.deliveries as NotificationDelivery[] : [];
}

export async function markAllNotificationsRead(surface: NotificationSurface) {
  const response = await fetch(`/api/notifications/read-all?surface=${encodeURIComponent(surface)}`, {
    method: "POST",
    headers: { Accept: "application/json" },
  });
  if (!response.ok) throw new Error(`notifications_read_all_failed_${response.status}`);
  return response.json();
}

export async function markNotificationRead(deliveryId: string) {
  const response = await fetch(`/api/notifications/${encodeURIComponent(deliveryId)}/read`, {
    method: "POST",
    headers: { Accept: "application/json" },
  });
  if (!response.ok) throw new Error(`notification_read_failed_${response.status}`);
  return response.json();
}
