How to clamp rotation between negative and positive value

I am trying to clamp my rotation between -20 and 45 but i tried somethings and i still couldnt do it.

I even tried to use only positive values like 330 or something it has a problem with the maximum value being 45 and then it freaks out. I have tried some stuff but im not getting there this is what i have got now. Any help is appreciated thanks.

 Vector3 clampedTurret = new Vector3(turretToClamp.turret.transform.eulerAngles.x, turretToClamp.turret.transform.eulerAngles.y, turretToClamp.turret.transform.eulerAngles.z);
     float zValue = clampedTurret.z;
 
                 if (zValue - 360 < turretToClamp.minAngle)
                 {
                     zValue = turretToClamp.minAngle + 360;
                     chng = true;
                 }
                 if (zValue > turretToClamp.maxAngle)
                 {
                     zValue = turretToClamp.maxAngle;
                     chng = true;
                 }
     
                 if (zValue < 0)
                     zValue = zValue + 360;
                 if (zValue > 360)
                     zValue = 0;
     
                 clampedTurret.z = zValue;

public float minAngle = -20;
public float maxAngle = 40;

    private void Update()
    {
        // get relative range +/-
        float relRange = (maxAngle - minAngle) / 2f;

        // calculate offset
        float offset = maxAngle - relRange;

        // convert to a relative value
        Vector3 angles = turretToClamp.turret.transform.eulerAngles;
        float z = ((angles.z + 540) % 360) - 180 - offset;

        // if outside range
        if (Mathf.Abs(z) > relRange)
        {
            angles.z = relRange * Mathf.Sign(z) + offset;
            turretToClamp.turret.transform.eulerAngles = angles;
        }
    }

@unit_nick This solution seems to work when facing one direction using -15 and 15 min/max angles but when my object changes direction and I try to adjust the min and max angles to 165 and 195 the object can’t go above 180 degrees and gets locked to the min 165 angle. Do you know why this could be happening?