import { apiClient } from '@/shared/api/client'

import type { ApiResponse, PaginatedResult } from '@/shared/types/types'
import type { RealnameStatusValue, RiskStatus, UserStatus } from '@/shared/types/status'

export interface AdminUserItem {
  id: number
  phone: string
  nickname: string
  realname_status: RealnameStatusValue
  risk_status: RiskStatus
  credit_score: number
  deposit_free_quota_cent: number
  deposit_free_used_cent: number
  deposit_free_remaining_cent: number
  status: UserStatus
  order_count: number
  listing_count: number
  dispute_count: number
  last_login_at?: string
  created_at: string
  updated_at: string
}

export interface AdminUserQuery {
  keyword?: string
  status?: '' | UserStatus
  has_deposit_free_quota?: boolean
}

export async function fetchAdminUsers(page = 1, pageSize = 20, query: AdminUserQuery = {}) {
  const params: Record<string, unknown> = { page, page_size: pageSize }
  if (query.keyword) params.keyword = query.keyword
  if (query.status) params.status = query.status
  if (query.has_deposit_free_quota) params.has_deposit_free_quota = true
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<AdminUserItem>>>(
    '/admin/users',
    {
      params,
    }
  )
  return data.data
}

export async function freezeAdminUser(id: number, reason: string) {
  const { data } = await apiClient.post<ApiResponse<AdminUserItem>>(`/admin/users/${id}/freeze`, {
    reason,
  })
  return data.data
}

export async function unfreezeAdminUser(id: number) {
  const { data } = await apiClient.post<ApiResponse<AdminUserItem>>(`/admin/users/${id}/unfreeze`)
  return data.data
}

export async function setAdminUserDepositFreeQuota(id: number, amountCent: number) {
  const { data } = await apiClient.post<ApiResponse<AdminUserItem>>(
    `/admin/users/${id}/deposit-free-quota`,
    { amount_cent: amountCent }
  )
  return data.data
}

export async function revokeAdminUserRealname(id: number, reason: string) {
  const { data } = await apiClient.post<ApiResponse<AdminUserItem>>(
    `/admin/users/${id}/revoke-realname`,
    { reason }
  )
  return data.data
}

export async function manualAdminUserRealname(
  id: number,
  payload: { name: string; idNo: string; reason: string }
) {
  const { data } = await apiClient.post<ApiResponse<AdminUserItem>>(
    `/admin/users/${id}/manual-realname`,
    {
      name: payload.name,
      id_no: payload.idNo,
      reason: payload.reason,
    }
  )
  return data.data
}
