'use server';

import { fetchJson, getAccessToken, getRefreshToken } from '@/lib/utils/server';

// RefreshToken으로 AccessToken 갱신
export async function refreshAccessToken(): Promise<boolean>
{
	const refreshToken = await getRefreshToken();
	if (!refreshToken) {
		return false;
	}

    return await fetchJson('/api/auth/refresh-token', {
        method: 'POST',
        body: JSON.stringify({ RefreshToken: refreshToken })
    }).then(res => res.success);
}

// 로그인 확인
export async function checkAuthServer(): Promise<boolean>
{
	const accessToken = await getAccessToken();
	if (accessToken) {
		try {
			const payload = JSON.parse(
                Buffer.from(accessToken.split('.')[1], 'base64').toString()
            );

			if (payload.exp * 1000 > Date.now()) {
				return true;
			}
		} catch {

		}
	}

	return await refreshAccessToken();
}