"use server";
import { redis } from "@/lib/redis";
import { functionRetrieveUserSelection } from "@/apifetchers/utils";
import { ClientMenu } from "@/types/mutual/context/validations";
import { getCompleteFromRedis, setCompleteToRedis } from "@/apifetchers/mutual/context/complete/fetch";
import { AuthError } from "@/types/mutual/context/validations";

const getMenuFromRedis = async (): Promise<ClientMenu> => {
    try {
        const decrpytUserSelection = await functionRetrieveUserSelection()
        const redisKey = decrpytUserSelection?.redisKey;
        if (!redisKey) throw new AuthError("No redis key found");
        const result = await redis.get(`${redisKey}`);
        if (!result) throw new AuthError("No data found in redis");
        const parsedResult = JSON.parse(result);
        if (!parsedResult.menu) throw new AuthError("No menu found in redis");
        return parsedResult.menu;
    } catch (error) { if (error instanceof AuthError) { throw error } else { throw new AuthError(error instanceof Error ? error.message : "Unknown error") } }
}

const setMenuToRedis = async (menuObject: ClientMenu) => {
    try {
        const decrpytUserSelection = await functionRetrieveUserSelection()
        if (!decrpytUserSelection) throw new AuthError("No user selection found");
        const redisKey = decrpytUserSelection?.redisKey;
        if (!redisKey) throw new AuthError("No redis key found");
        if (!menuObject) throw new AuthError("No menu object provided");
        const oldData = await getCompleteFromRedis();
        if (!oldData) throw new AuthError("No old data found in redis");
        await setCompleteToRedis({ ...oldData, menu: menuObject });
        return true;
    } catch (error) { if (error instanceof AuthError) { throw error } else { throw new AuthError(error instanceof Error ? error.message : "Unknown error") } }
}

export { getMenuFromRedis, setMenuToRedis };
