
/**
 * @author: Hemal
 * File: getPropertyDetails.ts
 * Purpose: This is the API call for the property details.
 * It returns the property details based on the slug.
 * It is used in the server side rendering.
 */
import { PropertyResponse } from "../types/api/property.type"
import { API_ENDPOINTS } from "../utils/commonVariables"
import * as Sentry from '@sentry/nextjs'
import { serverEncryptWithHMAC, serverDecrypWithHMAC } from "../utils/encryptionFunctions"

/**
 * @param params - The slug of the property.
 * @returns The property details based on the slug.
 */
export default async function getPropertyDetails(params: string) {
    const isEncryptionEnabled = process.env.NEXT_PUBLIC_API_ENCRYPTION_ENABLED === 'true'

    const finalPayload = isEncryptionEnabled
        ? serverEncryptWithHMAC({ slug: params })
        : { slug: params }

    try {
        const data = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}${API_ENDPOINTS.PROPERTY_DETAILS}`,
            {
                method: 'POST',
                body: JSON.stringify(finalPayload),
                headers: {
                    'Content-Type': 'application/json',
                    usertype: 'guest',
                },
                cache: 'no-store',
            }
        )

        const response: PropertyResponse = await data.json()

       
        const responseData = isEncryptionEnabled
            ? serverDecrypWithHMAC(response as any)
            : response

        if (!responseData?.data) {
            Sentry.captureException(responseData, {
                tags: {
                    api_url: API_ENDPOINTS.PROPERTY_DETAILS || 'unknown',
                },
                extra: {
                    requestData: finalPayload,
                    responseData: responseData,
                },
            })
        }

        return responseData
    } catch (error) {
        Sentry.captureException(error, {
            tags: {
                api_url: API_ENDPOINTS.PROPERTY_DETAILS || 'unknown',
            },
            extra: {
                requestData: finalPayload,
                responseData: error,
            },
        })
    }
}
