import "server-only" import { SEARCH_TYPE_REDEMPTION } from "../../../../../constants/booking" import { unauthorizedError } from "../../../../../errors" import { safeProtectedServiceProcedure } from "../../../../../procedures" import { getRedemptionTokenSafely } from "../../../../../utils/getRedemptionTokenSafely" import { getUserPointsBalance } from "../../../../../utils/getUserPointsBalance" import { getRoomsAvailability } from "../../../services/getRoomsAvailability" import { mergeRoomTypes } from "../../../utils" import { selectRateRoomsAvailabilityInputSchema } from "./schema" export const rooms = safeProtectedServiceProcedure .input(selectRateRoomsAvailabilityInputSchema) .use(async ({ ctx, input, next }) => { if (input.booking.searchType === SEARCH_TYPE_REDEMPTION) { if (ctx.session?.token.access_token) { const pointsValue = await getUserPointsBalance(ctx.session) const token = getRedemptionTokenSafely(ctx.session, ctx.serviceToken) if (pointsValue && token) { return next({ ctx: { token: token, userPoints: pointsValue ?? 0, }, input, }) } } throw unauthorizedError() } return next({ ctx: { token: ctx.serviceToken, }, }) }) .query(async function ({ ctx, input }) { input.booking.rooms = input.booking.rooms.map((room) => ({ ...room, bookingCode: room.bookingCode || input.booking.bookingCode, })) const availability = await getRoomsAvailability( input, ctx.token, ctx.serviceToken, ctx.userPoints ) for (const room of availability) { if (!room || "error" in room) { continue } room.roomConfigurations = mergeRoomTypes(room.roomConfigurations) } return availability })