/**
 * 用户管理服务
 * 负责用户数据的API调用
 */

import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';

/** 用户列表项 */
export interface UserListItem {
  accountId: string;
  accountSequence: string;
  avatar: string | null;
  nickname: string | null;
  phoneNumberMasked: string | null;
  personalAdoptions: number;
  teamAddresses: number;
  teamAdoptions: number;
  provincialAdoptions: {
    count: number;
    percentage: number;
  };
  cityAdoptions: {
    count: number;
    percentage: number;
  };
  referrerId: string | null;
  ranking: number | null;
  selfPrePlantingPortions: number;
  teamPrePlantingPortions: number;
  status: 'active' | 'frozen' | 'deactivated';
  isOnline: boolean;
}

/** 用户详情 */
export interface UserDetail extends UserListItem {
  kycStatus: string;
  registeredAt: string;
  lastActiveAt: string | null;
}

/** 用户列表响应 */
export interface UserListResponse {
  items: UserListItem[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

/** 用户统计 */
export interface UserStats {
  totalUsers: number;
  activeUsers: number;
  frozenUsers: number;
  verifiedUsers: number;
}

/** 用户列表查询参数 */
export interface UserListParams {
  keyword?: string;
  status?: string;
  kycStatus?: string;
  hasInviter?: boolean;
  minAdoptions?: number;
  maxAdoptions?: number;
  registeredAfter?: string;
  registeredBefore?: string;
  page?: number;
  pageSize?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

/**
 * 用户管理服务
 * 注意：apiClient 响应拦截器已解包 response.data，直接返回数据
 */
export const userService = {
  /**
   * 获取用户列表
   */
  async getUsers(params: UserListParams = {}): Promise<UserListResponse> {
    return apiClient.get(API_ENDPOINTS.USERS.LIST, { params });
  },

  /**
   * 获取用户详情
   */
  async getUserDetail(id: string): Promise<UserDetail> {
    return apiClient.get(API_ENDPOINTS.USERS.DETAIL(id));
  },

  /**
   * 获取用户统计
   */
  async getUserStats(): Promise<UserStats> {
    return apiClient.get(API_ENDPOINTS.USERS.STATS);
  },

  /**
   * 导出用户数据
   */
  async exportUsers(params: UserListParams = {}): Promise<Blob> {
    return apiClient.get(API_ENDPOINTS.USERS.EXPORT, {
      params,
      responseType: 'blob',
    });
  },
};

export default userService;
