import { ChildBedMapEnum } from "@/types/components/bookingWidget/enums"
import type { Child } from "@/types/components/hotelReservation/selectRate/selectRate"
import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"

export function convertToChildType(
  childrenAges: number[],
  childBedPreferences: BookingConfirmation["booking"]["childBedPreferences"]
): Child[] {
  const lookup = childBedPreferences.reduce(
    (preferences, preference) => {
      preferences[preference.bedType] = preference.quantity
      return preferences
    },
    {
      Crib: 0,
      ExtraBed: 0,
      ParentsBed: 0,
      Unknown: 0,
    }
  )

  const adultsAndOrCribKids = childrenAges.filter((childAge) => childAge <= 2)
  const adultsAndOrExtraBedKids = childrenAges.filter(
    (childAge) => childAge >= 3 && childAge <= 5
  )
  const extraBedKids = childrenAges.filter((childAge) => childAge >= 6)

  const cribKids = adultsAndOrCribKids.map((age) => {
    if (lookup.Crib) {
      lookup.Crib = lookup.Crib - 1
      return {
        age,
        bed: ChildBedMapEnum.IN_CRIB,
      }
    }

    lookup.ParentsBed = lookup.ParentsBed - 1
    return {
      age,
      bed: ChildBedMapEnum.IN_ADULTS_BED,
    }
  })

  const adultOrExtraKids = adultsAndOrExtraBedKids.map((age) => {
    if (lookup.ParentsBed) {
      lookup.ParentsBed = lookup.ParentsBed - 1
      return {
        age,
        bed: ChildBedMapEnum.IN_ADULTS_BED,
      }
    }

    if (lookup.ExtraBed) {
      lookup.ExtraBed = lookup.ExtraBed - 1
      return {
        age,
        bed: ChildBedMapEnum.IN_EXTRA_BED,
      }
    }

    return {
      age,
      bed: ChildBedMapEnum.UNKNOWN,
    }
  })

  const extraKids = extraBedKids.map((age) => {
    if (lookup.ExtraBed) {
      lookup.ExtraBed = lookup.ExtraBed - 1
      return {
        age,
        bed: ChildBedMapEnum.IN_EXTRA_BED,
      }
    }
    return {
      age,
      bed: ChildBedMapEnum.UNKNOWN,
    }
  })

  return [...cribKids, ...adultOrExtraKids, ...extraKids]
}
