import { apiClient } from './api'

export interface Permission {
  id: number
  resource: string
  action: string
  description?: string | null
}

export interface Role {
  id: number
  name: string
  description?: string | null
  is_system: boolean
  permissions: Permission[]
  user_count: number
  created_at: string
  updated_at: string
}

export interface RoleCreate {
  name: string
  description?: string
  permission_ids?: number[]
}

export interface RoleUpdate {
  name?: string
  description?: string
  permission_ids?: number[]
}

export const roleService = {
  async getRoles(): Promise<Role[]> {
    const response = await apiClient.get('/roles/')
    return response.data
  },

  async getPermissions(): Promise<Permission[]> {
    const response = await apiClient.get('/roles/permissions')
    return response.data
  },

  async createRole(data: RoleCreate): Promise<Role> {
    const response = await apiClient.post('/roles/', data)
    return response.data
  },

  async updateRole(roleId: number, data: RoleUpdate): Promise<Role> {
    const response = await apiClient.put(`/roles/${roleId}`, data)
    return response.data
  },

  async deleteRole(roleId: number): Promise<{ message: string }> {
    const response = await apiClient.delete(`/roles/${roleId}`)
    return response.data
  },

  async updateUserRoles(userId: number, roleIds: number[]): Promise<{ message: string; user_id: number; role_ids: number[] }> {
    const response = await apiClient.put(`/users/${userId}/roles`, { role_ids: roleIds })
    return response.data
  }
}
