package prototool

import (
	"reflect"
	"time"

	"google.golang.org/protobuf/types/known/durationpb"
)

// NotNil ensures that the memory that the field pointer is pointing to is not nil.
// field must be a valid pointer. It's target is checked for nil-ness and populated if it's nil.
func NotNil(field any) {
	v := reflect.ValueOf(field)
	vValue := v.Elem() // follow the pointer
	if !vValue.IsNil() {
		return
	}
	vValue.Set(reflect.New(vValue.Type().Elem()))
}

func DefaultVal[V comparable](v *V, defaultValue V) {
	var zero V
	if *v == zero {
		*v = defaultValue
	}
}

func DefaultValPtr[V any](v **V, defaultValue V) {
	if *v == nil {
		*v = &defaultValue
	}
}

func DefaultSlice[V any](v *[]V, defaultValue []V) {
	if len(*v) == 0 {
		*v = defaultValue
	}
}

func Duration(d **durationpb.Duration, defaultValue time.Duration) {
	if *d == nil {
		*d = durationpb.New(defaultValue)
	}
}
