import { formatPrice } from "@/utils/numberFormatting"

import type { IntlShape } from "react-intl"

import type { BookingConfirmationRoom } from "@/types/components/hotelReservation/bookingConfirmation/bookingConfirmation"
import { BreakfastPackageEnum } from "@/types/enums/breakfast"
import { CurrencyEnum } from "@/types/enums/currency"
import type {
  BookingConfirmationSchema,
  PackageSchema,
} from "@/types/trpc/routers/booking/confirmation"

export function mapRoomState(
  booking: BookingConfirmationSchema,
  room: BookingConfirmationRoom,
  intl: IntlShape
) {
  const breakfastPackage = booking.packages.find(
    (pkg) => pkg.code === BreakfastPackageEnum.REGULAR_BREAKFAST
  )
  const breakfastIncluded =
    booking.packages.some(
      (pkg) => pkg.code === BreakfastPackageEnum.FREE_MEMBER_BREAKFAST
    ) || booking.rateDefinition.breakfastIncluded

  let breakfast: false | undefined | PackageSchema
  if (breakfastPackage) {
    breakfast = breakfastPackage
  } else if (!breakfastIncluded) {
    breakfast = false
  }

  let formattedRoomCost = formatPrice(
    intl,
    booking.roomPrice,
    booking.currencyCode
  )
  if (booking.roomPoints) {
    formattedRoomCost = formatPrice(
      intl,
      booking.roomPoints,
      CurrencyEnum.POINTS,
      booking.roomPrice,
      booking.currencyCode
    )
  } else if (booking.cheques) {
    formattedRoomCost = formatPrice(
      intl,
      booking.cheques,
      CurrencyEnum.CC,
      booking.roomPrice,
      booking.currencyCode
    )
  } else if (booking.vouchers) {
    formattedRoomCost = formatPrice(
      intl,
      booking.vouchers,
      CurrencyEnum.Voucher
    )
  }

  return {
    adults: booking.adults,
    bedDescription: room.bedType.description,
    bookingCode: booking.bookingCode,
    breakfast,
    breakfastIncluded,
    cheques: booking.cheques,
    childrenAges: booking.childrenAges,
    childBedPreferences: booking.childBedPreferences,
    confirmationNumber: booking.confirmationNumber,
    currencyCode: booking.currencyCode,
    formattedRoomCost,
    fromDate: booking.checkInDate,
    name: room.name,
    packages: booking.packages,
    rateDefinition: booking.rateDefinition,
    refId: booking.refId,
    roomFeatures: booking.packages.filter((p) => p.type === "RoomFeature"),
    roomPoints: booking.roomPoints,
    roomPrice: booking.roomPrice,
    roomTypeCode: booking.roomTypeCode,
    toDate: booking.checkOutDate,
    totalPrice: booking.totalPrice,
    totalPriceExVat: booking.totalPriceExVat,
    vatAmount: booking.vatAmount,
    vouchers: booking.vouchers,
  }
}
