import type { JwtPayload } from 'jwt-decode';
import type { Ref, UnwrapRef } from 'vue';
import jwtDecode from 'jwt-decode';
import { isErrorResponse } from './base';
import { refresh_token } from './auth';

export async function check_token(
	token: TokenInjectType
): Promise<string | void> {
	if (!token.jwt.value) return token.logout();
	const payload = jwtDecode<JwtPayload>(token.jwt.value);
	if (!payload) return token.logout();
	// Expires in more than 60 Minute
	if (payload.exp && payload.exp > Math.floor(Date.now() / 1000 + 60 * 60))
		return token.jwt.value;
	const new_token = await refresh_token(token.jwt.value);
	if (isErrorResponse(new_token)) return token.logout();
	token.setToken(new_token.jwt);
	return new_token.jwt;
}

export type TokenInjectType = {
	jwt: Ref<UnwrapRef<string | null>>;
	setToken: (token: string) => void;
	logout: () => void;
};