import adminClient from "./client"
import type { ApiResponse } from "../../types"

const BASE = "/v1/admin/announcements"

export interface AdminAnnouncement {
  id: number
  title: string
  content: string
  category: string
  target_type: "all" | "specific" | string
  target_user_ids: number[] | null
  is_published: boolean
  published_at: string | null
  created_by: number | null
  created_at: string | null
}

export interface AdminAnnouncementList {
  items: AdminAnnouncement[]
  total: number
}

export interface AnnouncementPayload {
  title: string
  content: string
  category: string
  target_type: "all" | "specific"
  target_user_ids?: number[] | null
}

export interface NotificationBroadcastPayload {
  title: string
  content: string
  category: string
  level: "info" | "success" | "warning" | "error" | "urgent" | string
  target_type: "all" | "specific" | "role" | "member_level" | "agent"
  target_user_ids?: number[] | null
  target_role?: "user" | "admin" | "super_admin" | null
  target_member_level_ids?: number[] | null
  active_agents_only?: boolean
  action_label?: string | null
  action_url?: string | null
}

export interface NotificationBroadcastResult {
  matched: number
  sent: number
}

export async function listAnnouncements(params?: { limit?: number; offset?: number }) {
  const { data } = await adminClient.get<ApiResponse<AdminAnnouncementList>>(BASE, { params })
  return {
    items: Array.isArray(data.data?.items) ? data.data.items : [],
    total: Number(data.data?.total ?? 0) || 0,
  }
}

export async function createAnnouncement(payload: AnnouncementPayload) {
  const { data } = await adminClient.post<ApiResponse<AdminAnnouncement>>(BASE, payload)
  return data.data as AdminAnnouncement
}

export async function deleteAnnouncement(id: number) {
  const { data } = await adminClient.delete<ApiResponse<null>>(`${BASE}/${id}`)
  return data
}

export async function broadcastNotification(payload: NotificationBroadcastPayload) {
  const { data } = await adminClient.post<ApiResponse<NotificationBroadcastResult>>(`${BASE}/notifications`, payload)
  return data.data as NotificationBroadcastResult
}
