/**
 * This is the API call for the CMS data.
 * It returns the CMS data based on the slug.
 * It is used in the server side rendering.
 */
import { CMSResponse } from '../types/api/cms.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 CMS data.
 * @returns The CMS data based on the slug.
 */
export default async function getCMSData(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.VIEW_CMS}`,
            {
                method: 'POST',
                body: JSON.stringify(finalPayload),
                headers: {
                    'Content-Type': 'application/json',
                    usertype: 'guest'
                },
                cache: 'no-store'
            }
        )

        const response: CMSResponse = await data.json()

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

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

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