import { metrics } from "@opentelemetry/api" import { homeHrefs } from "@/constants/homeHrefs" import { Lang } from "@/constants/languages" import { myStay } from "@/constants/routes/myStay" import { env } from "@/env/server" import * as api from "@/lib/api" import { encrypt } from "../utils/encryption" import type { FriendTransaction, Stay } from "./output" const meter = metrics.getMeter("trpc.user") const getProfileCounter = meter.createCounter("trpc.user.profile") const getProfileSuccessCounter = meter.createCounter( "trpc.user.profile-success" ) const getProfileFailCounter = meter.createCounter("trpc.user.profile-fail") async function updateStaysBookingUrl( data: Stay[], token: string, lang: Lang ): Promise async function updateStaysBookingUrl( data: FriendTransaction[], token: string, lang: Lang ): Promise async function updateStaysBookingUrl( data: Stay[] | FriendTransaction[], token: string, lang: Lang ) { // Temporary API call needed till we have user name in ctx session data getProfileCounter.add(1) console.info("api.user.profile updatebookingurl start", JSON.stringify({})) const apiResponse = await api.get(api.endpoints.v1.Profile.profile, { cache: "no-store", headers: { Authorization: `Bearer ${token}`, }, }) if (!apiResponse.ok) { getProfileFailCounter.add(1, { error: JSON.stringify(apiResponse) }) console.info( "api.user.profile updatebookingurl error", JSON.stringify({ error: apiResponse }) ) return data } const apiJson = await apiResponse.json() if (!apiJson.data?.attributes) { return data } getProfileSuccessCounter.add(1) console.info("api.user.profile updatebookingurl success", JSON.stringify({})) return data.map((d) => { const originalString = d.attributes.confirmationNumber.toString() + "," + apiJson.data.attributes.lastName const encryptedBookingValue = encrypt(originalString) // Construct URL using myStay route and append encrypted value const bookingUrlPath = encryptedBookingValue ? `${myStay[lang]}?RefId=${encryptedBookingValue}` : `${myStay[lang]}?bookingId=${d.attributes.confirmationNumber}&lastName=${apiJson.data.attributes.lastName}` // Construct full URL with domain const domain = homeHrefs[env.NODE_ENV][lang] const bookingUrl = new URL(bookingUrlPath, domain) // Update TLD based on language if (lang !== Lang.en) bookingUrl.host = bookingUrl.host.replace(".com", `.${lang}`) return { ...d, attributes: { ...d.attributes, bookingUrl: bookingUrl.toString(), }, } }) } export { updateStaysBookingUrl }