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

export interface CartItemSelection {
  variationId: string
  variationName: string
  optionId: string
  value: string
}

export interface CartItem {
  id: string
  storeItemId: string
  storeItemVariantId: string
  productId: string
  productTitle: string
  productNameFa: string
  productImage: string | null
  sku: string
  selections: CartItemSelection[]
  label: string
  quantity: number
  unitPrice: number
  compareAtPrice: number
  lineTotal: number
  stockQuantity: number | null
}

export interface Cart {
  id: string
  businessId: string
  items: CartItem[]
  itemCount: number
  subtotal: number
  updatedAt: string
}

export interface ShippingAddressInput {
  province: string
  city: string
  address: string
  postalCode: string
  landline?: string
}

export type CheckoutPaymentType = 'e_payment_gate' | 'transfer'

export type OnlineGatewayType = 'mellat_behpardakht' | 'saman_kish'

export interface CheckoutPaymentInput {
  type: CheckoutPaymentType
  gatewayType?: string
  transferAccount?: string
  transferRefNumber?: string
}

export interface CheckoutInput {
  addressId?: string
  shippingAddress?: ShippingAddressInput
  customerNotes?: string
  payment: CheckoutPaymentInput
}

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

export async function getCart(signal?: AbortSignal) {
  return apiRequest<{ cart: Cart }>(cartPath(), { auth: true, signal })
}

export async function addCartItem(storeItemVariantId: string, quantity = 1) {
  return apiRequest<{ message: string; cart: Cart }>(cartPath('/items'), {
    method: 'POST',
    auth: true,
    body: { storeItemVariantId, quantity },
  })
}

export async function updateCartItem(itemId: string, quantity: number) {
  return apiRequest<{ message: string; cart: Cart }>(cartPath(`/items/${itemId}`), {
    method: 'PATCH',
    auth: true,
    body: { quantity },
  })
}

export async function removeCartItem(itemId: string) {
  return apiRequest<{ message: string; cart: Cart }>(cartPath(`/items/${itemId}`), {
    method: 'DELETE',
    auth: true,
  })
}

export async function checkoutCart(input: CheckoutInput) {
  return apiRequest<{ message: string; order: Order }>(cartPath('/checkout'), {
    method: 'POST',
    auth: true,
    body: input,
  })
}
