import type { Room } from "@/types/hotel"

type RoomType = Room["roomTypes"][number]

// This util function filters room types to show only unique bed configurations
export default function getFilteredRoomTypes(roomTypes: RoomType[]) {
  const customOccupancyRoomTypes = roomTypes.filter(
    (roomType) => roomType.mainBed.type === "CustomOccupancy"
  )
  const otherRoomTypes = roomTypes.filter(
    (roomType) => roomType.mainBed.type !== "CustomOccupancy"
  )

  const filteredOtherRoomTypes = filterDuplicatesByDescription(otherRoomTypes)

  // If there are no CustomOccupancy room types, return just the filtered other types
  if (customOccupancyRoomTypes.length === 0) {
    return filteredOtherRoomTypes
  }

  // If there is only one CustomOccupancy room type, no need to find the best one
  if (customOccupancyRoomTypes.length === 1) {
    return [...filteredOtherRoomTypes, customOccupancyRoomTypes[0]]
  }

  // Find the CustomOccupancy room type with highest occupancy
  const bestCustomOccupancyRoomType = customOccupancyRoomTypes.reduce<RoomType>(
    (best, current) => {
      return current.occupancy.total > best.occupancy.total ? current : best
    },
    customOccupancyRoomTypes[0]
  )

  return [...filteredOtherRoomTypes, bestCustomOccupancyRoomType]
}

// Helper function to just filter duplicates by description
function filterDuplicatesByDescription(roomTypes: RoomType[]): RoomType[] {
  const uniqueRoomsByDescription: Record<string, RoomType> = {}

  roomTypes.forEach((roomType) => {
    const description = roomType.mainBed.description
    if (!uniqueRoomsByDescription[description]) {
      uniqueRoomsByDescription[description] = roomType
    }
  })

  return Object.values(uniqueRoomsByDescription)
}
