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

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

export interface RoleQueryParams {
  keyword?: string;
  status?: string;
  current?: number;
  size?: number;
}

function mapRoleToFrontend(r: any) {
  if (!r) return r;
  return {
    ...r,
    name: r.role_name,
    code: r.role_key,
    description: r.remark || "",
    createdAt: r.create_time,
    updatedAt: r.update_time,
  };
}

function mapRoleToBackend(data: Record<string, unknown>) {
  const result: Record<string, unknown> = { ...data };
  if (result.name !== undefined) { result.role_name = result.name; delete result.name; }
  if (result.code !== undefined) { result.role_key = result.code; delete result.code; }
  if (result.description !== undefined) { result.remark = result.description; delete result.description; }
  return result;
}

/**
 * 角色分页查询
 */
export async function getRoleList(params: Record<string, unknown>): Promise<ApiResponse<PageResult<any>>> {
  const keyword = (params.name as string) || (params.code as string) || (params.keyword as string) || undefined;
  const body: Record<string, unknown> = {};
  if (keyword) body.keyword = keyword;
  if (params.status) body.status = params.status;
  const res: any = await request.post("/sys/role/page", body, {
    params: {
      page: params.current || 1,
      size: params.pageSize || 10,
    },
  });
  if (res.code === 1 && res.data) {
    res.data.list = (res.data.list || []).map(mapRoleToFrontend);
  }
  return res;
}

/**
 * 角色列表（不分页）
 */
export async function getRoleAll(): Promise<ApiResponse<any[]>> {
  const res: any = await request.get("/sys/role/list");
  if (res.code === 1 && res.data) {
    res.data = (res.data || []).map(mapRoleToFrontend);
  }
  return res;
}

/**
 * 角色详情
 */
export async function getRoleById(id: string): Promise<ApiResponse<any>> {
  const res: any = await request.get("/sys/role/detail", { params: { id } });
  if (res.code === 1 && res.data) {
    res.data = mapRoleToFrontend(res.data);
  }
  return res;
}

/**
 * 新增/编辑角色
 */
export function saveRole(data: Record<string, unknown>): Promise<ApiResponse<any>> {
  return request.post("/sys/role/save", mapRoleToBackend(data));
}

// 兼容旧接口名
export const createRole = saveRole;
export const updateRole = saveRole;

/**
 * 删除角色
 */
export function deleteRole(id: string): Promise<ApiResponse<any>> {
  return request.post("/sys/role/delete", { id });
}
