Rotate the gameobject to the mouse is click

The following script does not turn object correctly most turns it sideways or in the opposite direction to the mouse is click.

public class MoveUnit : MonoBehaviour {

 
    private bool flag = false;

    private Vector3 endPoint;

    public float duration = 50.0f;
   
    private float yAxis;

    public Transform rotateObject;
    public int speed;

    void Start()
    {
        yAxis = gameObject.transform.position.y;
    }

    void Update()
    {

        RotateObject();
 
        if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
        {

            RaycastHit hit;

            Ray ray;
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
  
                flag = true;
  
                endPoint = hit.point;
 
                endPoint.y = yAxis;

            }
        }

        if (flag && !Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
        {
     
            gameObject.transform.position = Vector3.Lerp(gameObject.transform.position, endPoint, 1 / (duration * (Vector3.Distance(gameObject.transform.position, endPoint))));

        }

        else if (flag && Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
        {
            flag = false;
 
        }
    }

    void RotateObject()
    {
        Vector3 dir = new Vector3(endPoint.x, endPoint.y, endPoint.z);
        Quaternion lookRotation = Quaternion.LookRotation(dir);
        Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * speed).eulerAngles;
        partToRotate.rotation = Quaternion.Euler(rotation.x, rotation.y, rotation.z);

    }
}

try…

    public float degreesPerSecond = 90;

     void RotateObject()
    {
        var look= endPoint - partToRotate.position;
        var targetRot= Quaternion.LookRotation(look);
   
        // keep the math in Quaternion, it'll prevent the gimble lock
        partToRotate.rotation = Quaternion.RotateTowards(partToRotate.rotation, targetRot, Time.deltaTime * degreesPerSecond);
    }

also your Vector3.Lerp code is frame-dependent, so the speed won’t be consistent. try MoveTowards instead, specifying a speed instead of a duration

public float velocity;

 ...

if(flag)
{
   transform.position = Vector3.MoveTowards(transform.position, endPoint, Time.deltaTime * velocity);
   flag = !Mathf.Approximately(0,(transform.position-endPoint).sqrMagnitude);
}