import type { Role } from "./types"
import { apiClient } from "./client"
import type { PaginatedResponse, PaginationParams } from "./client"

// 将后端 Django Group 数据映射到前端 Role 类型
function mapBackendGroup(g: any): Role {
  return {
    id: String(g.id),
    name: g.name,
    description: undefined,
    permissions: g.permissions || [],
    userCount: g.user_count || 0,
    createdAt: undefined,
    updatedAt: undefined,
  }
}

// 获取角色(Group)列表
export const getRoles = async (params?: PaginationParams): Promise<PaginatedResponse<Role>> => {
  const page = params?.page || 1
  const pageSize = params?.pageSize || 10

  const response = await apiClient.get(`/user/groups/?page=${page}&page_size=${pageSize}`)

  const data = response.data?.data || response.data
  const results: any[] = data.results || (Array.isArray(data) ? data : [])
  const total = data.count || results.length

  return {
    items: results.map(mapBackendGroup),
    total,
    page,
    pageSize,
    totalPages: Math.ceil(total / pageSize),
  }
}

// 获取单个角色
export const getRole = async (id: string): Promise<Role> => {
  const response = await apiClient.get(`/user/groups/${id}/`)
  const data = response.data?.data || response.data
  return mapBackendGroup(data)
}

// 创建角色（需要管理员权限）
export const createRole = async (roleData: Partial<Role>): Promise<Role> => {
  const payload = {
    name: roleData.name,
  }

  const response = await apiClient.post(`/user/groups/`, payload)
  const data = response.data?.data || response.data
  return mapBackendGroup(data)
}

// 更新角色（需要管理员权限）
export const updateRole = async (id: string, roleData: Partial<Role>): Promise<Role> => {
  const payload: any = {}
  if (roleData.name !== undefined) payload.name = roleData.name

  const response = await apiClient.patch(`/user/groups/${id}/`, payload)
  const data = response.data?.data || response.data
  return mapBackendGroup(data)
}

// 删除角色（需要管理员权限）
export const deleteRole = async (id: string): Promise<boolean> => {
  await apiClient.delete(`/user/groups/${id}/`)
  return true
}
