import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

export interface BusinessCustomer {
  id: string
  cellNumber: string
  firstName: string | null
  lastName: string | null
  email: string | null
  label: string
}

export interface BusinessCustomerListItem extends BusinessCustomer {
  createdAt: string
  isEnabled: boolean
  /** Placeholder until orders stats API exists */
  orderCount?: number | null
  /** Placeholder until orders stats API exists */
  totalTransactionsIrt?: number | null
}

export interface CustomersListResponse {
  items: BusinessCustomerListItem[]
  total: number
  page: number
  pageSize: number
}

export interface ListCustomersParams {
  page?: number
  pageSize?: number
  name?: string
  cellNumber?: string
}

function businessPath(suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/customers${suffix}`
}

export async function listCustomers(
  params: ListCustomersParams = {},
  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)

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

export interface UpdateCustomerPayload {
  isEnabled?: boolean
  firstName?: string
  lastName?: string
  email?: string
  cellNumber?: string
}

export interface CreateCustomerPayload {
  cellNumber: string
  firstName: string
  lastName: string
  password?: string
  email?: string
}

export async function createCustomer(payload: CreateCustomerPayload) {
  return apiRequest<BusinessCustomerListItem & { isVerified: boolean; role: string }>(
    businessPath(),
    {
      method: 'POST',
      auth: true,
      body: payload,
    },
  )
}

export async function updateCustomer(userId: string, payload: UpdateCustomerPayload) {
  return apiRequest<BusinessCustomer & { isEnabled: boolean }>(`${businessPath(`/${userId}`)}`, {
    method: 'PATCH',
    auth: true,
    body: payload,
  })
}

export async function updateCustomerEnabled(userId: string, isEnabled: boolean) {
  return updateCustomer(userId, { isEnabled })
}

export async function removeCustomer(userId: string) {
  return apiRequest<{ success: boolean }>(`${businessPath(`/${userId}`)}`, {
    method: 'DELETE',
    auth: true,
  })
}

export async function searchCustomers(
  query: string,
  limit = 20,
  signal?: AbortSignal,
) {
  const q = query.trim()
  if (q.length < 2) {
    return { items: [] as BusinessCustomer[] }
  }

  return apiRequest<{ items: BusinessCustomer[] }>(
    `${businessPath('/search')}?q=${encodeURIComponent(q)}&limit=${limit}`,
    { auth: true, signal },
  )
}
