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

const getUserFromRedis = async (): Promise<ClientUser> => {
    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.user) throw new AuthError("No user found in redis");

        return parsedResult.user;
    } catch (error) {
        if (error instanceof AuthError) { throw error }
        throw new AuthError(error instanceof Error ? error.message : "Unknown error");
    }
}

const setUserToRedis = async (userObject: ClientUser) => {
    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 (!userObject) throw new AuthError("No user object provided");

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

        await setCompleteToRedis({ ...oldData, user: userObject });
        return true;
    } catch (error) {
        if (error instanceof AuthError) { throw error }
        throw new AuthError(error instanceof Error ? error.message : "Unknown error");
    }
}

export { getUserFromRedis, setUserToRedis };
