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

export interface UserQueryParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
}

export interface User {
  id: number;
  username: string;
  nickname: string;
  email?: string;
  phone?: string;
  gender?: 'male' | 'female';
  avatar?: string;
  status?: 'enabled' | 'disabled';
  tenantId?: number;
  validState?: number;
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
  tenant?: {
    id: number;
    name: string;
  };
  roles?: Array<{
    id: number;
    role: {
      id: number;
      name: string;
      code: string;
    };
  }>;
  contestJudges?: Array<{
    contest: {
      id: number;
      contestName: string;
      status: string;
    };
  }>;
}

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 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 deleteUser(id: number): Promise<void> {
  return await request.delete<any, void>(`/users/${id}`);
}

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