package config

import (
	"fmt"
	"os"
	"path"

	"github.com/spf13/viper"
)

// ReadConfigDir reads all config files from provided directory in alphabetical order
// and merge its content with current viper configuration.
func ReadConfigDir(v *viper.Viper, configDir string) error {
	entries, err := os.ReadDir(configDir)
	if err != nil {
		return err
	}

	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}
		ext := path.Ext(entry.Name())
		if ext != ".yaml" && ext != ".yml" && ext != ".json" {
			continue
		}

		if err = mergeConfig(v, path.Join(configDir, entry.Name())); err != nil {
			return err
		}
	}

	return nil
}

// mergeConfig reads config file and merge its content with current viper.
func mergeConfig(v *viper.Viper, fileName string) error {
	cv := viper.New()
	cv.SetConfigFile(fileName)
	err := cv.ReadInConfig()
	if err != nil {
		return fmt.Errorf("failed to read config: %w", err)
	}
	if err = v.MergeConfigMap(cv.AllSettings()); err != nil {
		return fmt.Errorf("failed to merge config: %w", err)
	}

	return nil
}