package utils

import (
	"errors"
	"strconv"
)

func OptionalBool(input *bool) bool {
	if input == nil {
		return false
	}

	return *input
}

func CreateOptionalBool(input bool) *bool {
	if input == false {
		return nil
	}

	return &input
}

// OptionalString converts a non-nil *string to the respective string or returns "".
func OptionalString(input *string) string {
	if input == nil {
		return ""
	}

	return *input
}

// OptionalInt converts a non-nil *int to the respective int, otherwise returns 0.
func OptionalInt(input *int) int {
	if input == nil {
		return 0
	}

	return *input
}

// CreateOptionalInt when given a zero value int (0), it returns a nil *int.
// Otherwise, it gives a proper *int with valid value.
func CreateOptionalInt(input int) *int {
	if input == 0 {
		return nil
	}

	return &input
}

// CreateOptionalString when given an empty string, it returns a nil *string.
// Otherwise, it gives a proper *string with valid value.
func CreateOptionalString(input string) *string {
	if input == "" {
		return nil
	}

	return &input
}

// GetNumberFromString converts a string to a number.
// Returns error if the query is not a number.
func GetNumberFromString(input string) (int, error) {
	for _, c := range input {
		if c < '0' || c > '9' {
			return 0, errors.New("invalid input")
		}
	}

	idAsInt, err := strconv.Atoi(input)
	if err != nil || idAsInt <= 0 {
		return 0, errors.New("invalid input")
	}

	return idAsInt, nil
}

type Number interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

// OptionalNumber converts a non-nil *NUMBER to the respective number value or returns 0.
func OptionalNumber[T Number](input *T) T {
	if input == nil {
		return 0
	}

	return *input
}

// CreateOptionalNumber when given an zero value NUMBER (0), it returns a nil *NUMBER, otherwise, it gives a proper *NUMBER with valid value.
func CreateOptionalNumber[T Number](input T) *T {
	if input == 0 {
		return nil
	}

	return &input
}

func IntToInt64Pointer(input *int) *int64 {
	if input == nil {
		return nil
	}
	val := int64(*input)
	return &val
}

func NumberToNumberPointer[T Number, Y Number](input *T) *Y {
	if input == nil {
		return nil
	}

	val := Y(*input)
	return &val
}
