import request from "@/utils/request";
import type { PaginationResponse } from "@/types/api";

export interface UserQueryParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
  userType?: "platform" | "org" | "judge" | "public";
  filterTenantId?: number;
  userSource?: "admin_created" | "self_registered";
  status?: "enabled" | "disabled";
}

export interface UserTenant {
  id: number;
  name: string;
  code: string;
  tenantType: string;
  isSuper: number;
}

export interface User {
  id: number;
  username: string;
  nickname: string;
  email?: string;
  phone?: string;
  gender?: "male" | "female";
  avatar?: string;
  status?: "enabled" | "disabled";
  userSource?: string;
  city?: string;
  birthday?: string;
  organization?: string;
  tenantId?: number;
  validState?: number;
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
  // 平铺的租户字段（后端直接返回）
  tenantName?: string;
  tenantCode?: string;
  tenantType?: string;
  tenantIsSuper?: number;
  // 兼容嵌套对象（详情接口可能返回）
  tenant?: UserTenant;
  roles?: Array<{
    id: number;
    role: {
      id: number;
      name: string;
      code: string;
    };
  }>;
  _count?: {
    parentRelations: number;
    contestRegistrations: number;
  };
  // 详情接口返回 — 子女账号（独立用户）
  parentRelations?: Array<{
    id: number;
    relationship?: string;
    controlMode: string;
    child: {
      id: number;
      username: string;
      nickname: string;
      avatar?: string;
      gender?: string;
      birthday?: string;
      city?: string;
      status?: string;
      createTime?: string;
    };
  }>;
  contestRegistrations?: Array<{
    id: number;
    registrationState: string;
    participantType: string;
    createTime: string;
    contest: { id: number; contestName: string; contestState: string };
    child?: { id: number; name: string };
  }>;
  contestJudges?: Array<{
    contest: {
      id: number;
      contestName: string;
      status: string;
    };
  }>;
}

export interface UserStats {
  total: number;
  platform: number;
  org: number;
  judge: number;
  public: number;
}

export interface CreateUserForm {
  username: string;
  password: string;
  nickname: string;
  email?: string;
  phone?: string;
  gender?: "male" | "female";
  avatar?: string;
  status?: "enabled" | "disabled";
  roleIds?: number[];
}

export interface UpdateUserForm {
  username?: string;
  password?: string;
  nickname?: string;
  email?: string;
  phone?: string;
  gender?: "male" | "female";
  avatar?: string;
  status?: "enabled" | "disabled";
  roleIds?: number[];
}

// 获取用户列表
export async function getUsersList(
  params: UserQueryParams
): Promise<PaginationResponse<User>> {
  const response = await request.get<any, PaginationResponse<User>>("/users", {
    params,
  });
  return response;
}

// 获取用户统计
export async function getUserStats(): Promise<UserStats> {
  const response = await request.get<any, UserStats>("/users/stats");
  return response;
}

// 获取单个用户详情
export async function getUserDetail(id: number): Promise<User> {
  const response = await request.get<any, User>(`/users/${id}`);
  return response;
}

// 创建用户
export async function createUser(data: CreateUserForm): Promise<User> {
  const response = await request.post<any, User>("/users", data);
  return response;
}

// 更新用户
export async function updateUser(
  id: number,
  data: UpdateUserForm
): Promise<User> {
  const response = await request.patch<any, User>(`/users/${id}`, data);
  return response;
}

// 切换用户状态
export async function updateUserStatus(
  id: number,
  status: "enabled" | "disabled"
): Promise<void> {
  await request.patch(`/users/${id}/status`, { status });
}

// 删除用户
export async function deleteUser(id: number): Promise<void> {
  return await request.delete<any, void>(`/users/${id}`);
}

// 兼容性导出：保留 usersApi 对象
export const usersApi = {
  getList: getUsersList,
  getStats: getUserStats,
  getDetail: getUserDetail,
  create: createUser,
  update: updateUser,
  updateStatus: updateUserStatus,
  delete: deleteUser,
};
