
/**
 * This is the API call for Profile View.
 * It returns Profile View data based on token
 * It is used in the server side rendering.
 */
import { API_ENDPOINTS, AUTH_COOKIES } from "../utils/commonVariables"
import { cookies } from 'next/headers'
import CryptoJS from 'crypto-js'
import * as Sentry from '@sentry/nextjs'
import { serverEncryptWithHMAC, serverDecrypWithHMAC } from "../utils/encryptionFunctions"

const ENCRYPTION_KEY = process.env.NEXT_PUBLIC_ENCRYPTION_KEY || 'default-key'

/**
 * Gets and decrypts a cookie value using Next.js 13+ cookies() API
 * @param {string} cookie - Encrypted cookie value
 * @returns {any} Decrypted and parsed cookie value, or null if invalid
 */
export const getEncryptedCookie = (cookie: any): any => {
    try {
        const decryptedBytes = CryptoJS.AES.decrypt(cookie, ENCRYPTION_KEY)
        const decryptedData = decryptedBytes.toString(CryptoJS.enc.Utf8)
        return JSON.parse(decryptedData)
    } catch (error) {
        console.error("Error decrypting cookie:", error)
        return null
    }
}

/**
 * @returns Profile View based on token
 */
export default async function getProfileView() {
    const cookieStore = await cookies()
    const cookie = cookieStore.get(AUTH_COOKIES.USER_TOKEN)?.value
    const authToken = (cookie && getEncryptedCookie(cookie)) || ""

    const isEncryptionEnabled = process.env.NEXT_PUBLIC_API_ENCRYPTION_ENABLED === "true"

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

    const headers: Record<string, string> = {
        "Content-Type": "application/json",
    }

    if (authToken) {
        headers["Authorization"] = `Bearer ${authToken}`
    }

    try {
        const data = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}${API_ENDPOINTS.VIEW_PROFILE}`,
            {
                method: "POST",
                body: JSON.stringify(finalPayload),
                headers,
                cache: "no-store",
            }
        )

        const response = await data.json()

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

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

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