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

export type OrderStatus =
  | 'pending'
  | 'confirmed'
  | 'processing'
  | 'shipped'
  | 'delivered'
  | 'cancelled'

export type OrderSource = 'website' | 'admin' | 'app'

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

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

export interface Order {
  id: string
  businessId: string
  orderNumber: string
  status: OrderStatus
  processStepId: string
  processStepLabel?: string | null
  processStepLabelFa?: string | null
  processStepColor?: string | null
  source: OrderSource
  subtotal: number
  shippingTotal: number
  discountTotal: number
  total: number
  shippingAddress: Record<string, unknown>
  addressId: string | null
  customerNotes: string | null
  adminNotes: string | null
  createdBy: string | null
  createdAt: string
  updatedAt: string
  customer: OrderCustomer
  items: OrderItem[]
}

export interface OrdersListResponse {
  items: Order[]
  total: number
  page: number
  pageSize: number
}

export interface ListOrdersParams {
  page?: number
  pageSize?: number
  status?: OrderStatus
  orderNumber?: string
  dateFrom?: string
  dateTo?: string
}

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

export async function listOrders(params: ListOrdersParams = {}, 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.status) q.set('status', params.status)
  if (params.orderNumber) q.set('orderNumber', params.orderNumber)
  if (params.dateFrom) q.set('dateFrom', params.dateFrom)
  if (params.dateTo) q.set('dateTo', params.dateTo)

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

export async function getOrder(orderId: string, signal?: AbortSignal) {
  return apiRequest<{ order: Order }>(businessPath(`/${orderId}`), { auth: true, signal })
}
