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

        const response: BlogResponse = await data.json()

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

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

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