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

export interface Role {
  id: number;
  name: string;
  code: string;
  description?: string;
  validState?: number;
  createBy?: number;
  updateBy?: number;
  createTime?: string;
  updateTime?: string;
  permissions?: Array<{
    id: number;
    permission: {
      id: number;
      name: string;
      code: string;
      resource: string;
      action: string;
    };
  }>;
}

export interface CreateRoleForm {
  name: string;
  code: string;
  description?: string;
  permissionIds?: number[];
}

export interface UpdateRoleForm {
  name?: string;
  code?: string;
  description?: string;
  permissionIds?: number[];
}

// 获取角色列表
export async function getRolesList(
  params: PaginationParams
): Promise<PaginationResponse<Role>> {
  const response = await request.get<any, PaginationResponse<Role>>("/api/roles", {
    params,
  });
  return response;
}

// 获取所有角色（不分页）
export async function getAllRoles(): Promise<Role[]> {
  const response = await request.get<any, Role[]>("/api/roles/all");
  return response;
}

// 获取单个角色详情
export async function getRoleDetail(id: number): Promise<Role> {
  const response = await request.get<any, Role>(`/api/roles/${id}`);
  return response;
}

// 创建角色
export async function createRole(data: CreateRoleForm): Promise<Role> {
  const response = await request.post<any, Role>("/api/roles", data);
  return response;
}

// 更新角色
export async function updateRole(
  id: number,
  data: UpdateRoleForm
): Promise<Role> {
  const response = await request.put<any, Role>(`/api/roles/${id}`, data);
  return response;
}

// 删除角色
export async function deleteRole(id: number): Promise<void> {
  return await request.delete<any, void>(`/api/roles/${id}`);
}

// 兼容性导出：保留 rolesApi 对象
export const rolesApi = {
  getList: getRolesList,
  getAll: getAllRoles,
  getDetail: getRoleDetail,
  create: createRole,
  update: updateRole,
  delete: deleteRole,
};
