import adminClient from "./client"
import type { NotificationItem, UnreadCount } from "../../api/notifications"

function listResult<T>(value: unknown): { items: T[]; total: number } {
  const data = value as { items?: unknown; total?: unknown } | null | undefined
  return {
    items: Array.isArray(data?.items) ? data.items as T[] : [],
    total: Number(data?.total ?? 0) || 0,
  }
}

export async function getAdminUnreadCount() {
  const res = await adminClient.get("/v1/notifications/unread-count")
  const data = res.data.data as Partial<UnreadCount> | null | undefined
  return {
    notifications: Number(data?.notifications ?? 0) || 0,
    announcements: Number(data?.announcements ?? 0) || 0,
    total: Number(data?.total ?? 0) || 0,
  }
}

export async function listAdminNotifications(params: {
  category?: string
  unread_only?: boolean
  limit?: number
  offset?: number
} = {}) {
  const res = await adminClient.get("/v1/notifications", { params })
  return listResult<NotificationItem>(res.data.data)
}

export async function markAdminNotificationRead(id: number) {
  const res = await adminClient.post(`/v1/notifications/${id}/read`)
  return res.data.data as { ok: boolean }
}
