import { CancellationRuleEnum, ChildBedTypeEnum } from "@/constants/booking"

export function formatChildBedPreferences({
  childrenAges,
  childBedPreferences,
}: {
  childrenAges: number[]
  childBedPreferences: Array<{
    bedType: string
    quantity: number
    code: string | null
  }>
}) {
  if (childrenAges.length === 0) return ""

  // Find the bed types from preferences
  const cribBed = childBedPreferences.find(
    (pref) => pref.bedType === ChildBedTypeEnum.Crib
  )?.bedType
  const parentsBed = childBedPreferences.find(
    (pref) => pref.bedType === ChildBedTypeEnum.ParentsBed
  )?.bedType
  const extraBed = childBedPreferences.find(
    (pref) => pref.bedType === ChildBedTypeEnum.ExtraBed
  )?.bedType

  // Step 1: Assign cribs to all children <= 2 years
  const preferences = childrenAges.map((age, index) => {
    if (age <= 2 && cribBed) return `${age}:${cribBed}`
    return { age, index }
  })

  // Filter out children who still need bed assignment
  const remainingChildren = preferences.filter(
    (pref): pref is { age: number; index: number } => typeof pref === "object"
  )

  // Step 2: Assign adults bed to one child <= 5 years if available
  const hasParentsBed = childBedPreferences.some(
    (pref) => pref.bedType === ChildBedTypeEnum.ParentsBed && pref.quantity > 0
  )

  if (hasParentsBed && parentsBed) {
    const youngChildIndex = remainingChildren.findIndex(
      (child) => child.age <= 5
    )
    if (youngChildIndex >= 0) {
      const child = remainingChildren[youngChildIndex]
      preferences[child.index] = `${child.age}:${parentsBed}`
      remainingChildren.splice(youngChildIndex, 1)
    }
  }

  // Step 3: Assign extra beds to remaining children
  if (extraBed) {
    remainingChildren.forEach(({ age, index }) => {
      preferences[index] = `${age}:${extraBed}`
    })
  }

  // Filter out any null values and join the results
  return `[${preferences.filter((pref) => typeof pref === "string").join(", ")}]`
}

export function hasModifiableRate(cancellationRule: string | null): boolean {
  return (
    cancellationRule === CancellationRuleEnum.CancellableBefore6PM ||
    cancellationRule === CancellationRuleEnum.Changeable
  )
}
