import { apiGet, apiPost, apiPut } from '@/lib/http'
import type { AdminPagination, AdminUserListItem } from '@/types/admin'

export type AdminRolePermission = {
  permissionKey: string
  permissionName: string
  permissionGroup: string
  description: string
  enabled: boolean
}

export type AdminRolePermissions = {
  roleKey: string
  roleName: string
  description: string
  permissions: AdminRolePermission[]
}

export function fetchAdminRolePermissions() {
  return apiGet<{ roles: AdminRolePermissions[] }>('/api/v1/admin/rbac')
}

export function updateAdminRolePermissions(roleKey: string, permissions: string[]) {
  return apiPut<AdminRolePermissions>(`/api/v1/admin/rbac/roles/${roleKey}/permissions`, {
    permissions,
  })
}

export function fetchAdminUsers(params?: Record<string, unknown>) {
  return apiGet<{ items: AdminUserListItem[]; pagination: AdminPagination }>(
    '/api/v1/admin/users',
    params,
  )
}

export function createAdminUser(payload: {
  username: string
  password: string
  role: string
  status?: string
}) {
  return apiPost<{ user: AdminUserListItem }>('/api/v1/admin/users', payload)
}

export function updateAdminUserRole(userId: number | string, payload: { role: string }) {
  return apiPost<{ user: AdminUserListItem }>(`/api/v1/admin/users/${userId}/role`, payload)
}

export function updateAdminUserStatus(userId: number | string, payload: { status: string }) {
  return apiPost<{ user: AdminUserListItem }>(`/api/v1/admin/users/${userId}/status`, payload)
}

export function resetAdminUserPassword(userId: number | string, payload: { password: string }) {
  return apiPost<{ user: AdminUserListItem }>(
    `/api/v1/admin/users/${userId}/reset-password`,
    payload,
  )
}
