import client from '@/api/client'

export interface DeviceInfo {
  id: string
  vendor: string
  tokenPreview: string
  platform: string | null
  deviceId: string | null
  brand: string | null
  model: string | null
  osVersion: string | null
  romVersion: string | null
  appVersion: string | null
  receivePush: boolean
  lastLoginAt: string | null
  updatedAt: string | null
}

export interface UserPushStatus {
  tokenType: string
  appKey: string
  userId: string
  online: boolean
  lastSeenAt: number
  canSendOfflineMessage: boolean
  deliverableDevice: DeviceInfo | null
  deliverableDevices: DeviceInfo[]
  devices: DeviceInfo[]
}

export interface DeviceLoginLog {
  id: string
  appKey: string
  userId: string
  vendor: string
  deviceId: string | null
  brand: string | null
  model: string | null
  platform: string | null
  osVersion: string | null
  appVersion: string | null
  createdAt: string
}

export interface PagedLogs {
  content: DeviceLoginLog[]
  total: number
  totalPages: number
}

export interface TestPushResult {
  appKey: string
  userId: string
  sent: boolean
  targetCount: number
  targets: DeviceInfo[]
}

export interface PushOperationLog {
  id: string
  appKey: string
  operator: string
  action: string
  resourceType: string
  resourceId?: string | null
  summary?: string | null
  detail?: string | null
  createdAt: string
}

export const pushAdminApi = {
  getUserStatus(appKey: string, userId: string) {
    return client.get<{ data: UserPushStatus }>('/push/admin/user-status', {
      params: { appKey, userId },
    })
  },

  getDeviceLogs(appKey: string, userId: string, page = 0, size = 20) {
    return client.get<{ data: PagedLogs }>('/push/admin/device-logs', {
      params: { appKey, userId, page, size },
    })
  },

  testOffline(appKey: string, userId: string, title: string, body: string, payload?: string, deviceId?: string | null) {
    return client.post<{ data: TestPushResult }>('/push/admin/test-offline', {
      appKey,
      userId,
      deviceId: deviceId ?? null,
      title,
      body,
      payload: payload ?? null,
    })
  },

  getOperationLogs(appKey: string, page = 0, size = 20) {
    return client.get<{ data: { content: PushOperationLog[]; total: number; totalPages: number } }>(
      '/push/admin/operation-logs', { params: { appKey, page, size } },
    )
  },

  getDeviceToken(appKey: string, deviceId: string) {
    return client.get<{ data: { token: string } }>(`/push/admin/devices/${deviceId}/token`, {
      params: { appKey },
    })
  },
}
