package config

import (
	"io"
	"log/slog"
	"os"
	"strings"

	"github.com/sethvargo/go-envconfig"
)

func secretLookuper() envconfig.LookuperFunc {
	return func(key string) (string, bool) {
		fileName := os.Getenv(key + "_FILE")
		if fileName == "" {
			return "", false
		}

		file, err := os.Open(fileName)
		if err != nil {
			slog.Error("could not read secret file", "path", fileName)
			return "", false
		}

		defer file.Close()

		sb := &strings.Builder{}

		_, err = io.Copy(sb, file)
		if err != nil {
			return "", false
		}

		return sb.String(), true
	}
}
