2D Platformer Enemy AI patrol

Hey guys, I am working on a 2D platformer and I was having trouble with my enemy ai. When the enemy reaches a wall or cliff it’s supposed to turn around but it currently just flips back and forth

public class EnemyPatrol : MonoBehaviour
{
    public LayerMask groundLayer;

    public float speed;

    public bool movingRight = true;
    public bool onGround, hitWall;

    public Transform groundDetection;

    void Update()
    {
        Patrol();
    }

    void Patrol()
    {
        onGround = Physics2D.Raycast(groundDetection.position, Vector2.down, 0.1f, groundLayer);

        hitWall = (Physics2D.Raycast(transform.position, Vector2.left, 0.75f, groundLayer) || Physics2D.Raycast(transform.position, Vector2.right, 0.75f, groundLayer));
        

        if (!movingRight)
        {
            transform.Translate(Vector2.left * speed * Time.deltaTime);
            ChangeDirection(-0.2f);
        }
        else
        {
            transform.Translate(Vector2.right * speed * Time.deltaTime);
            ChangeDirection(0.2f);
        }
            

        if (!onGround || hitWall)
        {
            if (movingRight)
            {
                movingRight = false;
            }
            else
            {
                movingRight = true;
            }
        }
    }

    void ChangeDirection(float direction)
    {
        Vector3 tempScale = transform.localScale;
        tempScale.x = direction;
        transform.localScale = tempScale;
    }
}

Update() is called every frame and it is likely being called multiple times per physics simulation causing rapid direction changes.

Instead of a Raycast() calculated every frame, you may want to consider placing Collider2D components on the relevant objects. Then your EnemyPatrol components can implement the OnCollisionEnter() method, take a look at with what it has collided, and take appropriate action. That will allow you to write code that responds to a specific event instead of using Raycast() to analyze the environment.
You can use a kind of collider called a trigger on invisible GameObjects that initiate actions. For example, a turn around point that the EnemyPatrol behavior knows to turn around if encountered, which can be logic in the OnCollisionEnter() method.