import { hasStoreItemDiscount } from './irtPrice'
import type { StoreProductListing } from './storeProductGroups'

export interface StoreListingFilters {
  name: string
  minPrice: number | null
  maxPrice: number | null
  onlyDiscounted: boolean
}

export const EMPTY_STORE_LISTING_FILTERS: StoreListingFilters = {
  name: '',
  minPrice: null,
  maxPrice: null,
  onlyDiscounted: false,
}

function listingEffectivePrice(listing: StoreProductListing): number | null {
  if (hasStoreItemDiscount(listing.displayPrice, listing.displayDiscountedPrice)) {
    return listing.displayDiscountedPrice
  }
  return listing.displayPrice
}

export function filterStoreListings(
  listings: StoreProductListing[],
  filters: StoreListingFilters,
): StoreProductListing[] {
  const nameQuery = filters.name.trim().toLowerCase()

  return listings.filter((listing) => {
    if (nameQuery) {
      const matchesTitle = listing.productTitle.toLowerCase().includes(nameQuery)
      const matchesFa = listing.productNameFa?.toLowerCase().includes(nameQuery)
      if (!matchesTitle && !matchesFa) return false
    }

    const price = listingEffectivePrice(listing)
    if (filters.minPrice !== null) {
      if (price === null || price < filters.minPrice) return false
    }
    if (filters.maxPrice !== null) {
      if (price === null || price > filters.maxPrice) return false
    }

    if (filters.onlyDiscounted) {
      const hasDiscount = listing.variants.some((variant) =>
        hasStoreItemDiscount(variant.price, variant.discountedPrice),
      )
      if (!hasDiscount) return false
    }

    return true
  })
}
