import { jwtDecode } from 'jwt-decode';

interface JWTPayload {
  staffId?: number;
  name?: string;
  iat: number;
  exp: number;
}

export const parseJWT = (token: string): JWTPayload | null => {
  try {
    return jwtDecode<JWTPayload>(token);
  } catch (error) {
    console.error('Failed to parse JWT:', error);
    return null;
  }
};

export const getUserIdFromToken = (token: string): number | null => {
  const payload = parseJWT(token);
  return payload?.staffId || null;
};

export const isTokenExpired = (token: string): boolean => {
  const payload = parseJWT(token);
  if (!payload?.exp) return true;
  return Date.now() >= payload.exp * 1000;
};