import { request } from '.'
import { mockAPI } from './mockData'
import { createMockWrapper } from '@/config/mock'

// 定义权限相关类型
export interface Permission {
  id: number
  name: string
  code: string
  description: string
  resource_type: string
  created_at: string
  updated_at: string
}

export interface PermissionQueryParams {
  page?: number
  pageSize?: number
  keyword?: string
}

export interface PermissionCreateData {
  name: string
  code: string
  description: string
  resource_type: string
}

export interface PermissionUpdateData {
  name?: string
  code?: string
  description?: string
  resource_type?: string
}

export interface ApiResponse<T = any> {
  success: boolean
  code: number
  message: string
  data: T
}

export interface PermissionListResponse {
  permissions: Permission[]
  pagination: {
    page: number
    pageSize: number
    total: number
    totalPages: number
  }
}

// 获取权限列表
export const getPermissions = (params?: PermissionQueryParams) =>
  request.get<ApiResponse<PermissionListResponse>>('/admin/permissions', { params })

// 获取权限详情
export const getPermission = (id: number) =>
  request.get<ApiResponse<Permission>>(`/admin/permissions/${id}`)

// 创建权限
export const createPermission = (data: PermissionCreateData) =>
  request.post<ApiResponse<Permission>>('/admin/permissions', data)

// 更新权限
export const updatePermission = (id: number, data: PermissionUpdateData) =>
  request.put<ApiResponse<Permission>>(`/admin/permissions/${id}`, data)

// 删除权限
export const deletePermission = (id: number) =>
  request.delete<ApiResponse<void>>(`/admin/permissions/${id}`)

// 批量删除权限
export const batchDeletePermissions = (ids: number[]) =>
  request.post<ApiResponse<{ message: string; affectedRows: number }>>('/admin/permissions/batch-delete', { ids })

// 开发环境使用模拟数据
const permissionAPI = createMockWrapper({
  getPermissions,
  getPermission,
  createPermission,
  updatePermission,
  deletePermission,
  batchDeletePermissions
}, mockAPI.permission)

export default permissionAPI