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

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

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

const setSettingsToRedis = async (settingsObject: ClientSettings) => {
    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 (!settingsObject) throw new AuthError("No settings object provided");

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

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

export { getSettingsFromRedis, setSettingsToRedis };
