/**
 * Validates a JWT token and checks if it has expired
 * @param token The JWT token to validate
 * @returns An object containing validation status and decoded token if valid
 */
export function validateJWT(token: string): { 
    valid: boolean; 
    expired: boolean; 
    decoded?: { [key: string]: any }; 
    error?: string 
} {
    try {
        // Check if token exists
        if (!token) {
            return { valid: false, expired: false, error: 'No token provided' };
        }

        // Split the token into parts
        const parts = token.split('.');
        if (parts.length !== 3) {
            return { valid: false, expired: false, error: 'Invalid token format' };
        }

        // Decode the payload (middle part)
        const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
        
        // Check expiration
        const currentTime = Math.floor(Date.now() / 1000);
        if (payload.exp && payload.exp < currentTime) {
            return { 
            valid: false, 
            expired: true, 
            decoded: payload, 
            error: 'Token has expired' 
            };
        }

        // Check if token is not valid before a specific time (if applicable)
        if (payload.nbf && payload.nbf > currentTime) {
            return { 
            valid: false, 
            expired: false, 
            decoded: payload, 
            error: 'Token not yet valid' 
            };
        }

        // If we reach here, token is valid
        return { valid: true, expired: false, decoded: payload };
    } catch (error) {
        return { 
            valid: false, 
            expired: false, 
            error: error instanceof Error ? error.message : 'Unknown error parsing token' 
        };
    }
}

/**
 * Helper function to get and validate JWT from localStorage
 * @returns The validation result containing token status
 */
export function getAndValidateJWT(): { 
    valid: boolean; 
    expired: boolean; 
    decoded?: { [key: string]: any }; 
    error?: string;
    token?: string;
} {
    try {
        const token = localStorage.getItem('jwt_token');
        if (!token) {
            return { valid: false, expired: false, error: 'No token stored' };
        }
        
        const result = validateJWT(token);
        return { ...result, token };
    } catch (error) {
        return { 
            valid: false, 
            expired: false, 
            error: error instanceof Error ? error.message : 'Error retrieving token' 
        };
    }
}