import { apiRequest } from '@/shared/api/client'
import type { CreatedIdResponse, PagedList, UserSummaryDto } from '@/shared/api/types'

type ListUsersParams = {
  page: number
  pageSize: number
  search?: string
  roleId?: string
  isBlocked?: boolean
  sort?: string
  desc?: boolean
}

export function listUsers(params: ListUsersParams) {
  const query = new URLSearchParams({
    page: String(params.page),
    pageSize: String(params.pageSize),
  })
  if (params.search) query.set('search', params.search)
  if (params.roleId) query.set('roleId', params.roleId)
  if (params.isBlocked !== undefined) query.set('isBlocked', String(params.isBlocked))
  if (params.sort) query.set('sort', params.sort)
  if (params.desc) query.set('desc', 'true')

  return apiRequest<PagedList<UserSummaryDto>>(`/admin/users?${query.toString()}`)
}

export function createUser(body: { userName: string; password: string; roleId: string }) {
  return apiRequest<CreatedIdResponse>('/admin/users', { method: 'POST', body })
}

export function blockUser(id: string) {
  return apiRequest<void>(`/admin/users/${id}/block`, { method: 'POST' })
}

export function unblockUser(id: string) {
  return apiRequest<void>(`/admin/users/${id}/unblock`, { method: 'POST' })
}

export function deleteUser(id: string) {
  return apiRequest<void>(`/admin/users/${id}`, { method: 'DELETE' })
}

export function resetUserPassword(id: string, newPassword: string) {
  return apiRequest<void>(`/admin/users/${id}/password`, {
    method: 'POST',
    body: { newPassword },
  })
}
