import type {
  Ancillaries,
  Ancillary,
  SelectedAncillary,
} from "@/types/components/myPages/myStay/ancillaries"
import type { User } from "@/types/user"

function filterPoints(ancillaries: Ancillaries, user: User | null) {
  return ancillaries.map((ancillary) => {
    return {
      ...ancillary,
      ancillaryContent: ancillary.ancillaryContent.map(
        ({ points, ...ancillary }) => ({
          ...ancillary,
          points: user ? points : undefined,
        })
      ),
    }
  })
}

export function generateUniqueAncillaries(
  ancillaries: Ancillaries
): Ancillary["ancillaryContent"] {
  const uniqueAncillaries = new Map(
    ancillaries.flatMap((a) => {
      return a.ancillaryContent.map((ancillary) => [ancillary.id, ancillary])
    })
  )
  return [...uniqueAncillaries.values()]
}

/**
 * Adds the breakfast package to the ancillaries
 *
 * Returns the ancillaries array with the breakfast package added to the
 * specified category. If the category doesn't exist it's created.
 */
function addBreakfastPackage(
  ancillaries: Ancillaries,
  breakfast: SelectedAncillary | undefined,
  categoryName: string
): Ancillaries {
  if (!breakfast) return ancillaries

  const category = ancillaries.find((a) => a.categoryName === categoryName)

  if (category) {
    const newCategory = {
      ...category,
      ancillaryContent: [breakfast, ...category.ancillaryContent],
    }

    return ancillaries.map((ancillary) =>
      ancillary.categoryName === categoryName ? newCategory : ancillary
    )
  }

  return [{ categoryName, ancillaryContent: [breakfast] }, ...ancillaries]
}

export function mapAncillaries(
  ancillaries: Ancillaries | null,
  breakfastAncillary: SelectedAncillary | undefined,
  user: User | null
) {
  const withBreakfastPopular = addBreakfastPackage(
    ancillaries ?? [],
    breakfastAncillary,
    "Popular"
  )
  const withBreakfastFood = addBreakfastPackage(
    withBreakfastPopular,
    breakfastAncillary,
    "Food"
  )

  return filterPoints(withBreakfastFood, user)
}
