import type { StoreItem } from '../services/storeItemService'
import type { StoreSpecialStoreItem } from '../types/storeSpecial'
import {
  groupStoreItemsByProduct,
  type StoreProductListing,
} from './storeProductGroups'

export interface SpecialProductListing extends StoreProductListing {
  storeItemId: string
}

function specialStoreItemToVariants(item: StoreSpecialStoreItem): StoreItem[] {
  const productTotalStock = item.variants.reduce(
    (sum, variant) => sum + (variant.stockQuantity ?? 0),
    0,
  )

  return item.variants.map((variant) => ({
    id: variant.id,
    storeItemId: item.id,
    productId: item.productId,
    productTitle: item.productTitle,
    productNameFa: item.productNameFa,
    productImage: item.productImage,
    productTotalStock,
    selections: variant.selections,
    label: variant.label,
    price: variant.price,
    discountedPrice: variant.discountedPrice,
    stockQuantity: variant.stockQuantity,
    rewardPoints: variant.rewardPoints,
    isFestival: variant.isFestival,
    sortOrder: variant.sortOrder,
    createdAt: '',
  }))
}

export function specialItemsToListings(items: StoreSpecialStoreItem[]): SpecialProductListing[] {
  const variants = items.flatMap(specialStoreItemToVariants)
  const listings = groupStoreItemsByProduct(variants)

  return listings.map((listing) => ({
    ...listing,
    storeItemId: listing.representative.storeItemId ?? listing.representative.id,
  }))
}
