package settings

import (
	"errors"
	"fmt"
	"log/slog"
	"os"
	"mocksnow/internal/utils"

	"gopkg.in/yaml.v2"
)

type Settings struct {
	SettingsPath string
	Logger       *slog.Logger
	Values       *SettingsYML
}

// SettingsYML struct holds various runtime data that is too cumbersome to specify via command line, eg replacement properties
type SettingsYML struct {
	Settings struct {
		TenantsToFilter    []string `yaml:"tenants_to_filter"`
		NodeChargeClusters []string `yaml:"node_charge_clusters"`
		SrmActiveActiveVms []string `yaml:"srm_activeactive_vms"`
		VcenterAddresses   []string `yaml:"vcenter_addresses"`
	} `yaml:"settings"`
}

func New(logger *slog.Logger, settingsPath string) *Settings {
	return &Settings{
		SettingsPath: utils.GetFilePath(settingsPath),
		Logger:       logger,
	}
}

func (s *Settings) ReadYMLSettings() error {
	// Create config structure
	var settings SettingsYML

	// Check for empty filename
	if len(s.SettingsPath) == 0 {
		return errors.New("settings file path not specified")
	}

	//path := utils.GetFilePath(settingsPath)

	// Open config file
	file, err := os.Open(s.SettingsPath)
	if err != nil {
		return fmt.Errorf("unable to open settings file : '%s'", err)
	}
	s.Logger.Debug("Opened settings yaml file", "file_path", s.SettingsPath)
	defer file.Close()

	// Init new YAML decode
	d := yaml.NewDecoder(file)

	// Start YAML decoding from file
	if err := d.Decode(&settings); err != nil {
		return fmt.Errorf("unable to decode settings file : '%s'", err)
	}

	s.Logger.Debug("Updating settings", "settings", settings)
	s.Values = &settings

	return nil
}
