package mutil

import (
	"os"
	"time"

	"github.com/tech/sendico/pkg/mlogger"
	"go.uber.org/zap"
)

func GetConfigValue(logger mlogger.Logger, varName, envVarName string, value, envValue *string) string {
	if value != nil && envValue != nil {
		logger.Warn("Both variable and environment variable are set, using environment variable value",
			zap.String("variable", varName), zap.String("environment_variable", envVarName), zap.String("value", *value), zap.String("env_value", os.Getenv(*envValue)))
	}

	if envValue != nil {
		return os.Getenv(*envValue)
	}

	if value != nil {
		return *value
	}

	return ""
}

func GetConfigIntValue(logger mlogger.Logger, varName, envVarName string, value *int, envValue *string) int {
	if value != nil && envValue != nil {
		logger.Warn("Both variable and environment variable are set, using environment variable value",
			zap.String("variable", varName), zap.String("environment_variable", envVarName), zap.Int("value", *value), zap.String("env_value", os.Getenv(*envValue)))
	}

	if envValue != nil {
		envStr := os.Getenv(*envValue)
		if envStr != "" {
			if parsed, err := time.ParseDuration(envStr + "s"); err == nil {
				return int(parsed.Seconds())
			}
			logger.Warn("Invalid environment variable value for timeout", zap.String("environment_variable", envVarName), zap.String("value", envStr))
		}
	}

	if value != nil {
		return *value
	}

	return 30 // Default timeout in seconds
}

func GetConfigBoolValue(logger mlogger.Logger, varName, envVarName string, value *bool, envValue *string) bool {
	if value != nil && envValue != nil {
		logger.Warn("Both variable and environment variable are set, using environment variable value",
			zap.String("variable", varName), zap.String("environment_variable", envVarName), zap.Bool("value", *value), zap.String("env_value", os.Getenv(*envValue)))
	}

	if envValue != nil {
		envStr := os.Getenv(*envValue)
		switch envStr {
		case "true", "1":
			return true
		case "false", "0":
			return false
		default:
			logger.Warn("Invalid environment variable value for boolean", zap.String("environment_variable", envVarName), zap.String("value", envStr))
		}
	}

	if value != nil {
		return *value
	}

	return false // Default for boolean
}
