import { apiClient } from "@/lib/api-client"

export interface NotificationSend {
  id: string
  title: string
  targetType: string
  targetCount: number
  readCount: number
  sentAt: string
}

export interface ComposeNotificationRequest {
  title: string
  message: string
  link?: string
  targetType: "ALL" | "SELECTED"
  recipientIds?: string[]
}

export interface ComposeNotificationResponse {
  id: string
  targetType: string
  targetCount: number
  sentAt: string
}

export interface NotificationSendsResponse {
  sends: NotificationSend[]
  totalElements: number
  totalPages: number
}

export async function composeNotification(
  request: ComposeNotificationRequest
): Promise<ComposeNotificationResponse> {
  return apiClient<ComposeNotificationResponse>("/notifications/compose", {
    method: "POST",
    body: JSON.stringify(request),
  })
}

export async function getNotificationSends(
  page = 0,
  size = 20
): Promise<NotificationSendsResponse> {
  return apiClient<NotificationSendsResponse>(
    `/notifications/sends?page=${page}&size=${size}`
  )
}

// Device registration
export interface DeviceTokenResponse {
  id: string
  platform: string
  deviceName: string
  lastUsedAt: string
  createdAt: string
}

export interface RegisterDeviceRequest {
  platform: "WEB" | "IOS" | "ANDROID"
  token: string
  deviceName?: string
}

export async function registerDevice(
  request: RegisterDeviceRequest
): Promise<DeviceTokenResponse> {
  return apiClient<DeviceTokenResponse>("/notifications/devices", {
    method: "POST",
    body: JSON.stringify(request),
  })
}

export async function getDevices(): Promise<{
  devices: DeviceTokenResponse[]
}> {
  return apiClient<{ devices: DeviceTokenResponse[] }>("/notifications/devices")
}

export async function unregisterDevice(id: string): Promise<void> {
  await apiClient<void>(`/notifications/devices/${id}`, { method: "DELETE" })
}

export async function getVapidKey(): Promise<{
  publicKey: string
  configured: string
}> {
  return apiClient<{ publicKey: string; configured: string }>(
    "/notifications/devices/vapid-key"
  )
}

// Notification preferences
export interface NotificationPreferences {
  IN_APP: boolean
  EMAIL: boolean
  WEB_PUSH: boolean
  MOBILE_PUSH: boolean
}

export async function getNotificationPreferences(): Promise<{
  preferences: NotificationPreferences
}> {
  return apiClient<{ preferences: NotificationPreferences }>(
    "/notifications/preferences"
  )
}

export async function updateNotificationPreferences(
  preferences: Partial<NotificationPreferences>
): Promise<{ preferences: NotificationPreferences }> {
  return apiClient<{ preferences: NotificationPreferences }>(
    "/notifications/preferences",
    {
      method: "PUT",
      body: JSON.stringify({ preferences }),
    }
  )
}
