import request from '@/utils/request'
import type { PageResponse } from './user.api'
import { RoleStatus } from '@/constants/status'

export interface Role {
  id: number
  roleName: string
  roleKey: string
  roleSort: number
  status: RoleStatus
  permissions: Permission[]
  createdAt: string
  updatedAt: string
}

export interface Permission {
  id: number
  name: string
  code: string
  resource: string
  action: string
}

export interface CreateRoleRequest {
  roleName: string
  roleKey: string
  roleSort: number
  permissions: number[]
}

export interface UpdateRoleRequest {
  roleName?: string
  roleKey?: string
  roleSort?: number
  status?: RoleStatus
  permissions?: number[]
}

export interface RolePageRequest {
  page: number
  size: number
  roleName?: string
  roleKey?: string
  status?: string
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

export const roleApi = {
  getAll: () => 
    request.get<Role[]>('/roles'),
  
  getPage: (params: RolePageRequest) => 
    request.get<PageResponse<Role>>('/roles/page', { params }),
  
  getById: (id: number) => 
    request.get<Role>(`/roles/${id}`),
  
  create: (data: CreateRoleRequest) => 
    request.post<Role>('/roles', data),
  
  update: (id: number, data: UpdateRoleRequest) => 
    request.put<Role>(`/roles/${id}`, data),
  
  delete: (id: number) => 
    request.delete<void>(`/roles/${id}`),
  
  batchDelete: (ids: number[]) => 
    request.post<void>('/roles/batch-delete', { ids }),
  
  updateStatus: (id: number, status: 'ACTIVE' | 'INACTIVE') => 
    request.put<void>(`/roles/${id}/status`, { status }),
  
  assignPermissions: (id: number, permissionIds: number[]) => 
    request.post<void>(`/roles/${id}/permissions`, { permissionIds }),
  
  getPermissions: (id: number) => 
    request.get<Permission[]>(`/roles/${id}/permissions`),
  
  getAllPermissions: () => 
    request.get<Permission[]>('/permissions'),
}
