import _get from 'lodash/get'
import _isEmpty from 'lodash/isEmpty'

export interface IAddOnsData {
  add_on_groups: Array<{ [key: string]: any }>;
  add_ons: Array<[]>;
}

export const addonsWithGroupsAdapter = (data: IAddOnsData) => {
  const addonsData = { ...data }
  const addOnsGroups = _get(addonsData, 'add_on_groups', [])
  const addons = _get(addonsData, 'add_ons', [])

  if (!_isEmpty(addOnsGroups)) {
    const addOnGroupsWithVariants: any = []
    const addOnsWithoutVariants: any = []

    addons.forEach((addon: any) => {
      if (addon.attributes.addOnGroupId) {
        // Collect addons groups inside with their variants
        const currentGroupId = addon.attributes.addOnGroupId
        const exsistingGroupIndex = addOnGroupsWithVariants.findIndex(
          (item: any) => item.id === currentGroupId
        )

        if (addOnGroupsWithVariants[exsistingGroupIndex]) {
          const addOnGroup = addOnGroupsWithVariants[exsistingGroupIndex]
          addOnGroupsWithVariants[exsistingGroupIndex] = {
            ...addOnGroup,
            variants: [...addOnGroup.variants, ...addon.attributes],
          }
        } else {
          const group =
            addOnsGroups.find(group => group.attributes.id === currentGroupId) || {}

          addOnGroupsWithVariants.push({
            ...group.attributes,
            variants: [...addon.attributes],
          })
        }
      } else {
        addOnsWithoutVariants.push(addon.attributes)
      }
    })

    return addOnGroupsWithVariants.concat(addOnsWithoutVariants)
  }

  // Adapt only simple addons data
  const adaptedAddons = (addons as any[]).map((addon: any) => ({
    ...addon.attributes,
  }))
  return adaptedAddons
}

export const cartAdapter = (cart: any) => {
  const cartData = _get(cart, 'data.attributes', [])
  const { expiresAt, cart: carts_arr } = cartData
  const { id, quantity } = carts_arr[0] || {}

  return { id, quantity, expiresAt }
}
