// Package config leest de configuratie van de backup server.
package config

import (
	"fmt"
	"net/url"
	"os"
	"strings"
	"time"

	"gitlab.com/Timfa/bluegit/internal/apppaths"
	"gopkg.in/yaml.v3"
)

// DefaultDataDir is de standaard gegevensmap.
func DefaultDataDir() string {
	return apppaths.DataDir("/var/lib/bluegit-backup", "BlueGit-backup")
}

// DefaultConfigPath is waar een oude config.yml nog kan staan.
func DefaultConfigPath() string {
	return apppaths.ConfigFile("", "BLUEGIT_BACKUP_CONFIG", "bluegit-backup.yml", "/etc/bluegit-backup/config.yml", "BlueGit-backup")
}

// Config is de draaiende configuratie van de backup server.
// Instellingen staan in data_dir/settings.yml; een oude config.yml wordt
// één keer overgenomen.
type Config struct {
	// Listen is waar de backup server luistert (plain HTTP; TLS doet een
	// proxy ervoor als dat nodig is).
	Listen string `yaml:"listen"`
	// PublicURL is het adres waarop BlueGit deze server bereikt, voor
	// meldingen, de archieflijst en rollback.
	PublicURL string `yaml:"public_url"`
	// DataDir bevat de draaiende kopie, de archieven en de koppeling.
	DataDir string `yaml:"data_dir"`
	// ArchiveInterval: zo vaak wordt de hele kopie gecomprimeerd en
	// opgeslagen. Standaard 24h (dagelijks).
	ArchiveInterval Duration `yaml:"archive_interval"`
	// RetentionDays: archieven ouder dan dit worden verwijderd. 0 = nooit
	// op leeftijd. Het nieuwste archief blijft altijd staan.
	RetentionDays int `yaml:"retention_days"`
	// MinFreeMB: zakt de vrije ruimte op DataDir hieronder, dan gaat het
	// oudste archief weg (het nieuwste blijft altijd staan).
	MinFreeMB int64 `yaml:"min_free_mb"`
	// RateLimitKiB begrenst het downloaden van BlueGit, in KiB/s.
	// Standaard 1024. 0 = geen limiet.
	RateLimitKiB int64 `yaml:"rate_limit_kib"`
	// FullSyncInterval: ook zonder melding wordt zo vaak gesynchroniseerd.
	FullSyncInterval Duration `yaml:"full_sync_interval"`
	// MinSyncInterval: na een melding wacht de server minstens zo lang
	// sinds de vorige sync, zodat een drukke BlueGit niet elke seconde een
	// databasekopie hoeft te maken.
	MinSyncInterval Duration `yaml:"min_sync_interval"`
}

// Duration leest "24h", "30m" enzovoort.
type Duration struct{ time.Duration }

// UnmarshalYAML leest een Go-duur of een aantal seconden.
func (d *Duration) UnmarshalYAML(n *yaml.Node) error {
	s := strings.TrimSpace(n.Value)
	if s == "" {
		return nil
	}
	if strings.HasSuffix(s, "d") {
		var days int
		if _, err := fmt.Sscanf(s, "%dd", &days); err == nil {
			d.Duration = time.Duration(days) * 24 * time.Hour
			return nil
		}
	}
	v, err := time.ParseDuration(s)
	if err != nil {
		return fmt.Errorf("ongeldige duur %q", s)
	}
	d.Duration = v
	return nil
}

// MarshalYAML schrijft de duur terug als tekst.
func (d Duration) MarshalYAML() (any, error) { return d.String(), nil }

// Defaults vult lege velden.
func (c *Config) Defaults() {
	if c.Listen == "" {
		c.Listen = "0.0.0.0:8080"
	}
	if c.DataDir == "" {
		c.DataDir = DefaultDataDir()
	}
	if c.ArchiveInterval.Duration == 0 {
		c.ArchiveInterval.Duration = 24 * time.Hour
	}
	if c.RetentionDays == 0 {
		c.RetentionDays = 30
	}
	if c.RetentionDays < 0 {
		c.RetentionDays = 0
	}
	if c.MinFreeMB == 0 {
		c.MinFreeMB = 1024
	}
	if c.RateLimitKiB == 0 {
		c.RateLimitKiB = 1024
	}
	if c.RateLimitKiB < 0 {
		c.RateLimitKiB = 0
	}
	if c.FullSyncInterval.Duration == 0 {
		c.FullSyncInterval.Duration = time.Hour
	}
	if c.MinSyncInterval.Duration == 0 {
		c.MinSyncInterval.Duration = 10 * time.Second
	}
}

// Validate controleert de combinatie.
func (c Config) Validate() error {
	if c.ArchiveInterval.Duration < time.Second {
		return fmt.Errorf("archive_interval moet minstens 1s zijn")
	}
	if c.FullSyncInterval.Duration < time.Second || c.MinSyncInterval.Duration < 0 {
		return fmt.Errorf("full_sync_interval moet minstens 1s zijn")
	}
	if _, err := ParsePublicURL(c.PublicURL); err != nil {
		return err
	}
	return nil
}

// ParsePublicURL controleert een publiek adres. Leeg is toegestaan (tot
// er gekoppeld wordt). Een domein of een IP-adres mag; IPv6 tussen hakjes.
func ParsePublicURL(s string) (string, error) {
	s = strings.TrimRight(strings.TrimSpace(s), "/")
	if s == "" {
		return "", nil
	}
	u, err := url.Parse(s)
	if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
		return "", fmt.Errorf("public_url moet een http(s)-adres zijn, bijvoorbeeld http://backup.lan:8080 of http://192.168.1.50:8080")
	}
	if u.User != nil {
		return "", fmt.Errorf("public_url mag geen gebruikersnaam of wachtwoord bevatten")
	}
	return s, nil
}

// Load leest path. Een ontbrekend bestand geeft de standaardwaarden.
func Load(path string) (Config, error) {
	var c Config
	b, err := os.ReadFile(path)
	if err != nil && !os.IsNotExist(err) {
		return c, err
	}
	if err == nil {
		if err := yaml.Unmarshal(b, &c); err != nil {
			return c, fmt.Errorf("%s: %w", path, err)
		}
	}
	c.Defaults()
	return c, c.Validate()
}

// Example is een voorbeeld van het oude config.yml-formaat. Dat bestand is
// niet meer nodig; een bestaand exemplaar wordt één keer overgenomen.
func Example() string {
	return `# Dit bestand is niet meer nodig om bluegit-backup te draaien.
# Start met --data-dir of BLUEGIT_BACKUP_DATA_DIR (standaard
# /var/lib/bluegit-backup) en regel de rest in de webinterface
# (http://<server>:8080, Instellingen) of via de API.
# Een bestaand bestand op dit pad wordt één keer overgenomen in
# data_dir/settings.yml; daarna wint de webinterface.
listen: 0.0.0.0:8080
# Waar BlueGit deze server bereikt (domein of IP-adres).
public_url: http://192.168.1.50:8080
data_dir: /var/lib/bluegit-backup
archive_interval: 24h
retention_days: 30
min_free_mb: 1024
rate_limit_kib: 1024
full_sync_interval: 1h
min_sync_interval: 10s
`
}
