/**
 * This is the API call for the FAQs list.
 * It returns the FAQs list based on the page and perPage.
 * It is used in the server side rendering.
 */
import { FAQResponse, FAQsListPayload } from '../types/api/faqs.type'
import { API_ENDPOINTS } from '../utils/commonVariables'
import * as Sentry from '@sentry/nextjs'
import {
    decryptWithHMAC,
    encryptWithHMAC,
    serverDecrypWithHMAC,
    serverEncryptWithHMAC
} from '../utils/encryptionFunctions'
/**
 * @param payload - The payload for the FAQs list.
 * @returns The FAQs list based on the page and perPage.
 */

export default async function getFAQsList(payload: FAQsListPayload) {
    const isEncryptionEnabled =
        process.env.NEXT_PUBLIC_API_ENCRYPTION_ENABLED === 'true'


    const finalpayload = isEncryptionEnabled
        ? serverEncryptWithHMAC(payload)
        : payload


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

        const response: FAQResponse = await data.json()

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

        if (!responseData?.data) {
            Sentry.captureException(responseData, {
                tags: {
                    api_url: API_ENDPOINTS.LIST_FAQ || 'unknown'
                },
                extra: {
                    requestData: finalpayload,
                    responseData: responseData
                }
            })
        }
        return responseData
    } catch (error) {

        Sentry.captureException(error, {
            tags: {
                api_url: API_ENDPOINTS.LIST_FAQ || 'unknown'
            },
            extra: {
                requestData: finalpayload,
                responseData: error
            }
        })
    }
}
