package loader

import (
	"context"
	"fmt"
	"os"

	"github.com/tidbcloud/devops/pkg/infra/config"
	"github.com/tidbcloud/devops/pkg/infra/log"

	"gopkg.in/yaml.v3"
)

type ConfigurationSourceFile struct {
	filepath string
}

func NewConfigurationSourceFile(filePath string) *ConfigurationSourceFile {
	return &ConfigurationSourceFile{
		filepath: filePath,
	}
}

func (s *ConfigurationSourceFile) Load(ctx context.Context, pre *config.RootConfig) (*config.RootConfig, error) {
	log.FromContext(ctx).Info("loading config from file", "path", s.filepath)

	data, err := os.ReadFile(s.filepath)
	if err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	conf := &config.RootConfig{}
	err = yaml.Unmarshal(data, conf)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return conf, nil
}
