package db

import (
	"git.haelnorr.com/h/golib/env"
	"github.com/pkg/errors"
)

type Config struct {
	User     string // ENV DB_USER: Database user for authentication (required)
	Password string // ENV DB_PASSWORD: Database password for authentication (required)
	Host     string // ENV DB_HOST: Database host address (required)
	Port     uint16 // ENV DB_PORT: Database port (default: 5432)
	DB       string // ENV DB_NAME: Database name to connect to (required)
	SSL      string // ENV DB_SSL: SSL mode for connection (default: disable)

	// Backup configuration
	BackupDir       string // ENV DB_BACKUP_DIR: Directory for database backups (default: backups)
	BackupRetention int    // ENV DB_BACKUP_RETENTION: Number of backups to keep (default: 10)
}

func ConfigFromEnv() (any, error) {
	cfg := &Config{
		User:            env.String("DB_USER", ""),
		Password:        env.String("DB_PASSWORD", ""),
		Host:            env.String("DB_HOST", ""),
		Port:            env.UInt16("DB_PORT", 5432),
		DB:              env.String("DB_NAME", ""),
		SSL:             env.String("DB_SSL", "disable"),
		BackupDir:       env.String("DB_BACKUP_DIR", "backups"),
		BackupRetention: env.Int("DB_BACKUP_RETENTION", 10),
	}

	// Validate SSL mode
	validSSLModes := map[string]bool{
		"disable":     true,
		"require":     true,
		"verify-ca":   true,
		"verify-full": true,
		"allow":       true,
		"prefer":      true,
	}
	if !validSSLModes[cfg.SSL] {
		return nil, errors.Errorf("Invalid DB_SSL value: %s. Must be one of: disable, allow, prefer, require, verify-ca, verify-full", cfg.SSL)
	}

	// Check required fields
	if cfg.User == "" {
		return nil, errors.New("Envar not set: DB_USER")
	}
	if cfg.Password == "" {
		return nil, errors.New("Envar not set: DB_PASSWORD")
	}
	if cfg.Host == "" {
		return nil, errors.New("Envar not set: DB_HOST")
	}
	if cfg.DB == "" {
		return nil, errors.New("Envar not set: DB_NAME")
	}
	if cfg.BackupRetention < 1 {
		return nil, errors.New("DB_BACKUP_RETENTION must be at least 1")
	}

	return cfg, nil
}
