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

const getSelectionFromRedis = async (): Promise<ClientSelection> => {
    try {
        const decrpytUserSelection = await functionRetrieveUserSelection();
        const redisKey = decrpytUserSelection?.redisKey;
        if (redisKey === "default") { return { selectionList: [], activeSelection: {} } }
        const result = await redis.get(`${redisKey}`);
        if (!result) { return { selectionList: [], activeSelection: {} } }
        const parsedResult = JSON.parse(result);
        if (!parsedResult.selection) { return { selectionList: [], activeSelection: {} } }
        return parsedResult.selection;
    } catch (error) { return { selectionList: [], activeSelection: {} } }
}

const setSelectionToRedis = async (selectionObject: ClientSelection) => {
    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 (!selectionObject) throw new AuthError("No selection object provided");

        const oldData = await getCompleteFromRedis();
        if (!oldData) throw new AuthError("No old data found in redis");

        await setCompleteToRedis({ ...oldData, selection: selectionObject })
        return true;
    } catch (error) {
        // Re-throw AuthError instances, wrap other errors as AuthError
        if (error instanceof AuthError) {
            throw error;
        } else {
            throw new AuthError(error instanceof Error ? error.message : "Unknown error");
        }
    }
}

export { getSelectionFromRedis, setSelectionToRedis };
