import type { ApiResponse, PageResult } from "@/types/api";

import { request } from "@/utils/request";

export interface UserQueryParams {
  keyword?: string;
  username?: string;
  email?: string;
  dept_id?: string;
  status?: string;
  current?: number;
  pageSize?: number;
  size?: number;
}

function mapUserToFrontend(u: any) {
  if (!u) return u;
  return {
    ...u,
    username: u.user_name,
    realName: u.nick_name,
    phone: u.phone || u.phonenumber,
    gender: u.sex === "0" ? "female" : "male",
    status: u.status === "0" ? "active" : "inactive",
    createdAt: u.create_time,
    updatedAt: u.update_time,
    deptName: u.dept_name || "",
    roles: (u.roles || []).map((r: any) => ({
      id: r.role_key,
      name: r.role_name,
      code: r.role_key,
    })),
  };
}

function mapUserToBackend(data: Record<string, unknown>) {
  const result: Record<string, unknown> = { ...data };
  if (result.username !== undefined) { result.user_name = result.username; delete result.username; }
  if (result.realName !== undefined) { result.nick_name = result.realName; delete result.realName; }
  if (result.gender === "male") { result.sex = "1"; delete result.gender; }
  if (result.gender === "female") { result.sex = "0"; delete result.gender; }
  if (result.status === "active") { result.status = "0"; }
  if (result.status === "inactive") { result.status = "1"; }
  return result;
}

/**
 * 用户分页查询
 */
export async function getUserList(params: UserQueryParams): Promise<ApiResponse<PageResult<any>>> {
  const keyword = params.keyword || params.username || params.email || undefined;
  const backendParams: Record<string, unknown> = {};
  if (keyword) backendParams.keyword = keyword;
  if (params.dept_id != null) backendParams.dept_id = params.dept_id;
  if (params.status === "active") backendParams.status = "0";
  else if (params.status === "inactive") backendParams.status = "1";
  else if (params.status) backendParams.status = params.status;
  const res: any = await request.post("/sys/user/page", backendParams, {
    params: {
      page: params.current || 1,
      size: params.pageSize || params.size || 10,
    },
  });
  if (res.code === 1 && res.data) {
    res.data.list = (res.data.list || []).map(mapUserToFrontend);
  }
  return res;
}

/**
 * 用户详情
 */
export async function getUserById(id: string): Promise<ApiResponse<any>> {
  const res: any = await request.get("/sys/user/detail", { params: { id } });
  if (res.code === 1 && res.data) {
    res.data = mapUserToFrontend(res.data);
  }
  return res;
}

/**
 * 新增/编辑用户
 */
export function saveUser(data: Record<string, unknown>): Promise<ApiResponse<any>> {
  return request.post("/sys/user/save", mapUserToBackend(data));
}

// 兼容旧接口名
export const createUser = saveUser;
export const updateUser = saveUser;

/**
 * 删除用户
 */
export function deleteUser(id: string): Promise<ApiResponse<any>> {
  return request.post("/sys/user/delete", { id });
}

/**
 * 重置密码
 */
export function resetPassword(data: { id: string; new_password: string }): Promise<ApiResponse<any>> {
  return request.post("/sys/user/reset_password", data);
}

/**
 * 分配角色
 */
export function assignRoles(data: { user_id: string; role_ids: string[] }): Promise<ApiResponse<any>> {
  return request.post("/sys/user/assign_roles", data);
}
