import { apiClient } from '@/shared/api/client'

import type { ApiResponse } from '@/shared/types/types'

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

export interface Role {
  id: number
  code: string
  name: string
  description: string
  perm_count: number
  permissions?: Permission[]
  created_at: string
  updated_at: string
}

export interface CreateRoleRequest {
  code: string
  name: string
  description?: string
}

export interface UpdateRoleRequest {
  name: string
  description?: string
}

export async function fetchRoles() {
  const { data } = await apiClient.get<ApiResponse<Role[]>>('/admin/roles')
  return data.data
}

export async function fetchRole(id: number) {
  const { data } = await apiClient.get<ApiResponse<Role>>(`/admin/roles/${id}`)
  return data.data
}

export async function createRole(req: CreateRoleRequest) {
  const { data } = await apiClient.post<ApiResponse<Role>>('/admin/roles', req)
  return data.data
}

export async function updateRole(id: number, req: UpdateRoleRequest) {
  const { data } = await apiClient.put<ApiResponse<Role>>(`/admin/roles/${id}`, req)
  return data.data
}

export async function deleteRole(id: number) {
  const { data } = await apiClient.delete<ApiResponse<{ deleted: boolean }>>(`/admin/roles/${id}`)
  return data.data
}

export async function assignRolePermissions(roleId: number, permissionIds: number[]) {
  const { data } = await apiClient.put<ApiResponse<{ updated: boolean }>>(`/admin/roles/${roleId}/permissions`, {
    permission_ids: permissionIds,
  })
  return data.data
}

export async function fetchPermissions() {
  const { data } = await apiClient.get<ApiResponse<Permission[]>>('/admin/permissions')
  return data.data
}
