package serverimp

import (
	"os"
	"strings"

	"github.com/tech/sendico/pkg/api/routers"
	"github.com/tech/sendico/pkg/db"
	"github.com/tech/sendico/pkg/server/grpcapp"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
)

type config struct {
	*grpcapp.Config `yaml:",inline"`

	// PermissionsDatabase points to the authorization store (policies/roles/assignments).
	// If omitted, startup falls back to Database for backward compatibility.
	PermissionsDatabase *db.Config `yaml:"permissions_database"`
}

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
	}

	cfg := &config{Config: &grpcapp.Config{}}
	if err := yaml.Unmarshal(data, cfg); err != nil {
		i.logger.Error("Failed to parse configuration", zap.Error(err))
		return nil, err
	}

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

	if cfg.GRPC == nil {
		cfg.GRPC = &routers.GRPCConfig{
			Network:          "tcp",
			Address:          ":50066",
			EnableReflection: true,
			EnableHealth:     true,
		}
	} else {
		if strings.TrimSpace(cfg.GRPC.Address) == "" {
			cfg.GRPC.Address = ":50066"
		}
		if strings.TrimSpace(cfg.GRPC.Network) == "" {
			cfg.GRPC.Network = "tcp"
		}
	}

	if cfg.Metrics == nil {
		cfg.Metrics = &grpcapp.MetricsConfig{Address: ":9416"}
	} else if strings.TrimSpace(cfg.Metrics.Address) == "" {
		cfg.Metrics.Address = ":9416"
	}

	return cfg, nil
}
