"use server";
import NextCrypto from "next-crypto";
import { cookieObject, tokenSecret } from "@/apifetchers/basics";
import { cookies } from "next/headers";

const nextCrypto = new NextCrypto(tokenSecret);

/**
 * Retrieves user selection from cookies with graceful fallback
 * @returns User selection object or default selection if not found
 */
const functionRetrieveUserSelection = async () => {
    try {
        const cookieStore = await cookies();
        const encrpytUserSelection = cookieStore.get("eys-sel")?.value || "";
        if (!encrpytUserSelection) { return { redisKey: "default", uuid: "", timestamp: new Date().toISOString() } }
        try {
            const decrpytUserSelection = await nextCrypto.decrypt(encrpytUserSelection);
            if (!decrpytUserSelection) { return { redisKey: "default", uuid: "", timestamp: new Date().toISOString() } }
            return JSON.parse(decrpytUserSelection);
        } catch (decryptError) { return { redisKey: "default", uuid: "", timestamp: new Date().toISOString() } }
    } catch (error) { return { redisKey: "default", uuid: "", timestamp: new Date().toISOString() } }
}

const functionSetUserSelection = async (userSelection: any) => {
    const cookieStore = await cookies();
    const encrpytUserSelection = await nextCrypto.encrypt(JSON.stringify(userSelection));
    if (!encrpytUserSelection) throw new Error("No user selection found");
    cookieStore.set({ name: "eys-sel", value: encrpytUserSelection, ...cookieObject });
}

const functionRemoveUserSelection = async () => {
    const cookieStore = await cookies();
    cookieStore.delete("eys-sel");
}

export { functionRetrieveUserSelection, functionSetUserSelection, functionRemoveUserSelection };