'use server';
import { nextCrypto, cookieOptions } from "@/fetchers/base";
import { cookies } from 'next/headers';

const ACCESS_TOKEN_COOKIE = 'acs';
const SELECT_TOKEN_COOKIE = 'slc';

export async function getCookieAccessToken() {
    try {
        const cookieStore = await cookies();
        const encryptedToken = cookieStore.get(ACCESS_TOKEN_COOKIE);
        if (!encryptedToken) {
            return undefined;
        }
        return { name: ACCESS_TOKEN_COOKIE, value: encryptedToken.value };
    } catch (error) {
        return undefined;
    }
}

export async function setCookieAccessToken(token: string) {
    try {
        const encryptedToken = await nextCrypto.encrypt(token);
        const cookieStore = await cookies();
        cookieStore.set(ACCESS_TOKEN_COOKIE, encryptedToken, {
            httpOnly: cookieOptions.httpOnly,
            secure: cookieOptions.secure,
            sameSite: cookieOptions.sameSite,
            path: cookieOptions.path,
            maxAge: cookieOptions.maxAge
        });
    } catch (error) {
    }
}

export async function getCookieSelectToken() {
    try {
        const cookieStore = await cookies();
        const encryptedToken = cookieStore.get(SELECT_TOKEN_COOKIE);
        if (!encryptedToken) {
            return undefined;
        }
        return { name: SELECT_TOKEN_COOKIE, value: encryptedToken.value };
    } catch (error) {
        return undefined;
    }
}

export async function setCookieSelectToken(token: string) {
    try {
        const encryptedToken = await nextCrypto.encrypt(token);
        const cookieStore = await cookies();
        cookieStore.set(SELECT_TOKEN_COOKIE, encryptedToken, {
            httpOnly: cookieOptions.httpOnly,
            secure: cookieOptions.secure,
            sameSite: cookieOptions.sameSite,
            path: cookieOptions.path,
            maxAge: cookieOptions.maxAge
        });
    } catch (error) {
    }
}

export async function removeAccessToken() {
    try {
        const cookieStore = await cookies();
        cookieStore.delete(ACCESS_TOKEN_COOKIE);
    } catch (error) {
    }
}

export async function removeSelectToken() {
    try {
        const cookieStore = await cookies();
        cookieStore.delete(SELECT_TOKEN_COOKIE);
    } catch (error) {
    }
}

export async function removeCookieTokens() {
    try {
        const cookieStore = await cookies();
        cookieStore.delete(ACCESS_TOKEN_COOKIE);
        cookieStore.delete(SELECT_TOKEN_COOKIE);
    } catch (error) {
    }
}
