import {
  clearGuestCart,
  loadGuestCart,
  type GuestCartItem,
} from '../lib/guestCart'
import { addCartItem, getCart, type Cart } from './cartService'

/**
 * Push guest-cart lines into the authenticated server cart.
 * Guest item `id` is the storeItemVariantId from the storefront.
 */
export async function syncGuestCartToServer(signal?: AbortSignal): Promise<Cart> {
  const guestItems = loadGuestCart()
  if (guestItems.length === 0) {
    const data = await getCart(signal)
    return data.cart
  }

  let cart: Cart | null = null

  for (const item of guestItems) {
    if (signal?.aborted) break
    const variantId = resolveVariantId(item)
    if (!variantId) continue
    const quantity = Math.max(1, Math.floor(item.quantity) || 1)
    const result = await addCartItem(variantId, quantity)
    cart = result.cart
  }

  if (!cart) {
    const data = await getCart(signal)
    cart = data.cart
  }

  if (cart.items.length > 0) {
    clearGuestCart()
  }

  return cart
}

function resolveVariantId(item: GuestCartItem): string | null {
  const id = item.id?.trim()
  if (!id) return null
  // Storefront guest cart uses variant id as item id
  return id
}
