'use client'

import { getCookie, setCookie, deleteCookie } from 'cookies-next'
import { decrypt, encrypt } from './Crypto'

type CookieOptions = {
    expires?: Date
    maxAge?: number
    path?: string
    secure?: boolean
    sameSite?: 'strict' | 'lax' | 'none'
}

/**
 * Set encrypted cookie
 */
export const setEncryptedCookie = (
    key: string,
    value: any,
    options?: CookieOptions
) => {
    try {
        const stringValue =
            typeof value === 'string' ? value : JSON.stringify(value)

        const encrypted = encrypt(stringValue)

        setCookie(key, encrypted, {
            path: '/',
            sameSite: 'lax',
            ...options
        })
    } catch (error) {
        console.error('Cookie encryption failed:', error)
    }
}

/**
 * Get decrypted cookie
 */
export const getDecryptedCookie = <T = string>(key: string): T | null => {
    try {
        const encrypted = getCookie(key)

        if (!encrypted || typeof encrypted !== 'string') return null

        const decrypted = decrypt(encrypted)

        try {
            return JSON.parse(decrypted) as T
        } catch {
            return decrypted as T
        }
    } catch (error) {
        console.error('Cookie decryption failed:', error)
        return null
    }
}

/**
 * Delete cookie
 */
export const removeCookie = (key: string) => {
    deleteCookie(key)
}
