package config

import (
	"fmt"
	"strconv"
	"strings"
)

func parseBool(value string) (bool, error) {
	switch strings.ToLower(strings.TrimSpace(value)) {
	case "1", "t", "true", "y", "yes", "on":
		return true, nil
	case "0", "f", "false", "n", "no", "off":
		return false, nil
	default:
		return false, fmt.Errorf("must be a boolean")
	}
}

func parseInt64(value string, min int64) (int64, error) {
	parsed, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
	if err != nil {
		return 0, fmt.Errorf("must be an integer")
	}
	if parsed < min {
		return 0, fmt.Errorf("must be at least %d", min)
	}
	return parsed, nil
}

func parseInt(value string, min int) (int, error) {
	parsed64, err := parseInt64(value, int64(min))
	if err != nil {
		return 0, err
	}
	if parsed64 > int64(^uint(0)>>1) {
		return 0, fmt.Errorf("is too large")
	}
	return int(parsed64), nil
}

func formatBool(value bool) string {
	if value {
		return "true"
	}
	return "false"
}
