import Cookies from "js-cookie"
import CryptoJS from "crypto-js"

export function setCookiesEncrypt<T>(
  param: string,
  data: T,
  options?: Cookies.CookieAttributes
) {
  const cookiesEncrypt = CryptoJS.AES.encrypt(
    JSON.stringify(data),
    `${param}_EncryptKey@silancar`
  ).toString()

  Cookies.set(param, cookiesEncrypt, options)
}

export function getCookiesDecrypt<T>(param: string): T | null {
  const cookiesEncrypt = Cookies.get(param)

  try {
    if (cookiesEncrypt) {
      const bytes = CryptoJS.AES.decrypt(
        cookiesEncrypt,
        `${param}_EncryptKey@silancar`
      )

      const decrypted = bytes.toString(CryptoJS.enc.Utf8)

      return JSON.parse(decrypted) as T
    }

    return null
  } catch (e) {
    console.error("Decrypt error:", e)
    return null
  }
}