// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package utils

import (
	"os"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestGetDurationFromEnv(t *testing.T) {
	// Test with no environment variable set (should return default value)
	defaultValue := 30 * time.Second
	result := GetDurationFromEnv("TEST_DURATION_ENV_NOT_SET", defaultValue)
	assert.Equal(t, defaultValue, result)

	// Test with valid duration string
	os.Setenv("TEST_DURATION_VALID", "5m")
	defer os.Unsetenv("TEST_DURATION_VALID")
	result = GetDurationFromEnv("TEST_DURATION_VALID", defaultValue)
	assert.Equal(t, 5*time.Minute, result)

	// Test with valid integer (seconds)
	os.Setenv("TEST_DURATION_SECONDS", "120")
	defer os.Unsetenv("TEST_DURATION_SECONDS")
	result = GetDurationFromEnv("TEST_DURATION_SECONDS", defaultValue)
	assert.Equal(t, 120*time.Second, result)

	// Test with invalid value (should return default)
	os.Setenv("TEST_DURATION_INVALID", "invalid")
	defer os.Unsetenv("TEST_DURATION_INVALID")
	result = GetDurationFromEnv("TEST_DURATION_INVALID", defaultValue)
	assert.Equal(t, defaultValue, result)
}

func TestGetIntFromEnv(t *testing.T) {
	// Test with no environment variable set (should return default value)
	defaultValue := 42
	result := GetIntFromEnv("TEST_INT_ENV_NOT_SET", defaultValue)
	assert.Equal(t, defaultValue, result)

	// Test with valid integer
	os.Setenv("TEST_INT_VALID", "100")
	defer os.Unsetenv("TEST_INT_VALID")
	result = GetIntFromEnv("TEST_INT_VALID", defaultValue)
	assert.Equal(t, 100, result)

	// Test with invalid value (should return default)
	os.Setenv("TEST_INT_INVALID", "invalid")
	defer os.Unsetenv("TEST_INT_INVALID")
	result = GetIntFromEnv("TEST_INT_INVALID", defaultValue)
	assert.Equal(t, defaultValue, result)
}
