package grpcapp

import (
	"strings"
	"time"

	"github.com/tech/sendico/pkg/api/routers"
	"github.com/tech/sendico/pkg/db"
	msg "github.com/tech/sendico/pkg/messaging"
)

const defaultShutdownTimeout = 15 * time.Second

type RuntimeConfig struct {
	ShutdownTimeoutSeconds int `yaml:"shutdown_timeout_seconds"`
}

func (c *RuntimeConfig) shutdownTimeout() time.Duration {
	if c == nil || c.ShutdownTimeoutSeconds <= 0 {
		return defaultShutdownTimeout
	}
	return time.Duration(c.ShutdownTimeoutSeconds) * time.Second
}

func (c *RuntimeConfig) ShutdownTimeout() time.Duration {
	return c.shutdownTimeout()
}

type Config struct {
	Runtime   *RuntimeConfig      `yaml:"runtime"`
	GRPC      *routers.GRPCConfig `yaml:"grpc"`
	Database  *db.Config          `yaml:"database"`
	Messaging *msg.Config         `yaml:"messaging"`
	Metrics   *MetricsConfig      `yaml:"metrics"`
}

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

func (c *MetricsConfig) listenAddress() string {
	if c == nil {
		return ""
	}
	if strings.TrimSpace(c.Address) == "" {
		return ":9400"
	}
	return c.Address
}
