import { clsx } from "clsx";
import { twMerge } from "tailwind-merge"
import { jwtDecode as decode } from "jwt-decode";
import { refreshToken } from "../api/auth.service";

export function cn(...inputs) {
  return twMerge(clsx(inputs));
}

let refreshPromise = null;

export async function jwtexp(token) {
  const decoded = decode(token);
  const currentTime = Date.now() / 1000;
  const tokenExp = decoded.exp;
  
  if (tokenExp < currentTime || tokenExp - currentTime < 120) {
    if (refreshPromise) {
      console.log("Refresh already in progress, waiting...");
      return await refreshPromise;
    }
    
    refreshPromise = (async () => {
      try {
        await refreshToken();
        return true;
      } catch (error) {
        console.error("Failed to refresh token:", error);
        return false;
      } finally {
        refreshPromise = null;
      }
    })();
    
    return await refreshPromise;
  }
  
  return true;
}