// Package serverimp contains the concrete discovery server implementation.
package serverimp

import (
	"os"
	"strings"

	msg "github.com/tech/sendico/pkg/messaging"
	"github.com/tech/sendico/pkg/server/grpcapp"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
)

const (
	defaultMetricsAddress         = ":9405"
	defaultShutdownTimeoutSeconds = 15
)

type config struct {
	Runtime   *grpcapp.RuntimeConfig `yaml:"runtime"`
	Messaging *msg.Config            `yaml:"messaging"`
	Metrics   *metricsConfig         `yaml:"metrics"`
	Registry  *registryConfig        `yaml:"registry"`
}

type metricsConfig struct {
	Address string `yaml:"address"`
}

type registryConfig struct {
	KVTTLSeconds *int `yaml:"kv_ttl_seconds"` //nolint:tagliatelle // matches config file format
}

func (i *Imp) loadConfig() (*config, error) {
	data, err := os.ReadFile(i.file)
	if err != nil {
		i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))

		return nil, err //nolint:wrapcheck
	}

	cfg := &config{}

	err = yaml.Unmarshal(data, cfg)
	if err != nil {
		i.logger.Error("Failed to parse configuration", zap.Error(err))

		return nil, err //nolint:wrapcheck
	}

	if cfg.Runtime == nil {
		cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: defaultShutdownTimeoutSeconds}
	}

	if cfg.Metrics != nil && strings.TrimSpace(cfg.Metrics.Address) == "" {
		cfg.Metrics.Address = defaultMetricsAddress
	}

	return cfg, nil
}
