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

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

export interface ShoppingCardItem {
  id: string
  storeItemVariantId: string | null
  productId: string
  productTitle: string
  variantSku: string | null
  unitPrice: number
  compareAtPrice: number | null
  quantity: number
  lineTotal: number
  selections: {
    variationId: string
    variationName: string
    optionId: string
    value: string
  }[]
}

export interface ShoppingCard {
  id: string
  businessId: string
  subtotal: number
  total: number
  createdBy: string | null
  createdAt: string
  updatedAt: string
  customer: ShoppingCardCustomer
  items: ShoppingCardItem[]
}

export interface ShoppingCardsListResponse {
  items: ShoppingCard[]
  total: number
  page: number
  pageSize: number
}

export interface ListShoppingCardsParams {
  page?: number
  pageSize?: number
  customerQuery?: string
  dateFrom?: string
  dateTo?: string
  minTotal?: number
  maxTotal?: number
}

export interface CreateShoppingCardPayload {
  customerUserId: string
  items: { storeItemVariantId: string; quantity: number }[]
}

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

export async function listShoppingCards(
  params: ListShoppingCardsParams = {},
  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.customerQuery) q.set('customerQuery', params.customerQuery)
  if (params.dateFrom) q.set('dateFrom', params.dateFrom)
  if (params.dateTo) q.set('dateTo', params.dateTo)
  if (params.minTotal !== undefined) q.set('minTotal', String(params.minTotal))
  if (params.maxTotal !== undefined) q.set('maxTotal', String(params.maxTotal))

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

export async function getShoppingCard(cardId: string, signal?: AbortSignal) {
  return apiRequest<{ card: ShoppingCard }>(businessPath(`/${cardId}`), {
    auth: true,
    signal,
  })
}

export async function createShoppingCard(payload: CreateShoppingCardPayload) {
  return apiRequest<{ message: string; card: ShoppingCard }>(businessPath(), {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function removeShoppingCard(cardId: string) {
  return apiRequest<{ message: string }>(businessPath(`/${cardId}`), {
    method: 'DELETE',
    auth: true,
  })
}
