import { apiRequest } from '../lib/api'
import type { RolesListResponse, UserSearchResponse, UsersListResponse } from '../types/user'

export interface ListUsersParams {
  page?: number
  pageSize?: number
  name?: string
  cellNumber?: string
  role?: string
  businessId?: number
  membership?: 'staff' | 'all'
}

export interface UpdateUserPayload {
  firstName?: string
  lastName?: string
  email?: string
  cellNumber?: string
}

export interface CreateUserPayload {
  cellNumber: string
  firstName: string
  lastName: string
  businessId: number
  password?: string
  email?: string
}

export async function searchUsers(q: string, limit = 20, signal?: AbortSignal) {
  const params = new URLSearchParams({ q, limit: String(limit) })
  return apiRequest<UserSearchResponse>(`/users/search?${params.toString()}`, {
    auth: true,
    signal,
  })
}

export async function listUsers(params: ListUsersParams, signal?: AbortSignal) {
  const q = new URLSearchParams()
  if (params.page !== undefined) q.set('page', String(params.page))
  if (params.pageSize !== undefined) q.set('pageSize', String(params.pageSize))
  if (params.name) q.set('name', params.name)
  if (params.cellNumber) q.set('cellNumber', params.cellNumber)
  if (params.role) q.set('role', params.role)
  if (params.businessId !== undefined) q.set('businessId', String(params.businessId))
  if (params.membership) q.set('membership', params.membership)

  const query = q.toString()
  const path = `/users${query ? `?${query}` : ''}`
  return apiRequest<UsersListResponse>(path, { auth: true, signal })
}

export async function listUserRoles(signal?: AbortSignal) {
  return apiRequest<RolesListResponse>('/roles?scope=global', { auth: true, signal })
}

export async function updateUserRole(userId: number | string, roleSlug: string) {
  return apiRequest<{ id: number; role: string; roles: string[] }>(`/users/${userId}/role`, {
    method: 'PATCH',
    auth: true,
    body: { roleSlug },
  })
}

export async function createUser(payload: CreateUserPayload) {
  return apiRequest(`/users`, {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateUser(userId: number | string, payload: UpdateUserPayload) {
  return apiRequest(`/users/${userId}`, {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

export async function adminResetUserPassword(userId: number | string, newPassword: string) {
  return apiRequest(`/users/${userId}/reset-password`, {
    method: 'POST',
    auth: true,
    body: { newPassword },
  })
}

export async function removeUser(userId: number | string) {
  return apiRequest(`/users/${userId}`, {
    method: 'DELETE',
    auth: true,
  })
}

export async function sendUserMessage(userId: number | string, message: string) {
  return apiRequest<{ enabled: boolean; message: string }>(`/users/${userId}/send-message`, {
    method: 'POST',
    auth: true,
    body: { message },
  })
}
