// Package config leest het YAML-configuratiebestand van BlueGit.
package config

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

	"gopkg.in/yaml.v3"
)

// Config is de installatie op de mini-PC.
type Config struct {
	BaseURL     string `yaml:"base_url"`
	Listen      string `yaml:"listen"`
	StoragePath string `yaml:"storage_path"`
	BehindProxy bool   `yaml:"behind_proxy"`
	Auth        Auth   `yaml:"auth"`
	Git         Git    `yaml:"git"`
	SSH         SSH    `yaml:"ssh"`
	CI          CI     `yaml:"ci"`
}

// Auth wijst naar auth.timfalken.com of naar de lokale ontwikkelmodus.
type Auth struct {
	Mode             string `yaml:"mode"`
	BaseURL          string `yaml:"base_url"`
	ClientID         string `yaml:"client_id"`
	ClientSecret     string `yaml:"client_secret"`
	ClientSecretFile string `yaml:"client_secret_file"`
	RedirectPath     string `yaml:"redirect_path"`
	UserAgent        string `yaml:"user_agent"`
	DevUser          string `yaml:"dev_user"`
	DevAuthID        int64  `yaml:"dev_auth_id"`
}

// Git wijst naar de git-binary en de standaardbranch van nieuwe repositories.
type Git struct {
	Binary        string `yaml:"binary"`
	DefaultBranch string `yaml:"default_branch"`
	HookBinary    string `yaml:"hook_binary"`
}

// SSH is de git-over-SSH-listener.
type SSH struct {
	Enabled bool   `yaml:"enabled"`
	Listen  string `yaml:"listen"`
}

// CI stuurt de Docker-runner.
type CI struct {
	Enabled     bool   `yaml:"enabled"`
	Docker      string `yaml:"docker_binary"`
	Concurrency int    `yaml:"concurrency"`
	Network     string `yaml:"network"`
	TimeoutSec  int    `yaml:"timeout_seconds"`
}

// Load leest path en vult ontbrekende waarden aan.
func Load(path string) (Config, error) {
	raw, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("config lezen: %w", err)
	}
	var c Config
	if err := yaml.Unmarshal(raw, &c); err != nil {
		return Config{}, fmt.Errorf("config: %w", err)
	}
	c.applyDefaults()
	if v := os.Getenv("BLUEGIT_STORAGE_PATH"); v != "" {
		c.StoragePath = v
	}
	if v := os.Getenv("BLUEGIT_LISTEN"); v != "" {
		c.Listen = v
	}
	if v := os.Getenv("BLUEGIT_AUTH_CLIENT_SECRET"); v != "" {
		c.Auth.ClientSecret = v
	}
	if c.Auth.ClientSecret == "" && c.Auth.ClientSecretFile != "" {
		b, err := os.ReadFile(c.Auth.ClientSecretFile)
		if err != nil {
			return Config{}, fmt.Errorf("clientgeheim: %w", err)
		}
		c.Auth.ClientSecret = strings.TrimSpace(string(b))
	}
	if err := c.Validate(); err != nil {
		return Config{}, err
	}
	return c, nil
}

func (c *Config) applyDefaults() {
	if c.Listen == "" {
		c.Listen = "127.0.0.1:8080"
	}
	if c.Auth.Mode == "" {
		c.Auth.Mode = "oauth"
	}
	if c.Auth.BaseURL == "" {
		c.Auth.BaseURL = "https://auth.timfalken.com"
	}
	if c.Auth.RedirectPath == "" {
		c.Auth.RedirectPath = "/auth/callback"
	}
	if c.Auth.UserAgent == "" {
		c.Auth.UserAgent = "BlueGitAccountClient/0.1"
	}
	if c.Auth.DevUser == "" {
		c.Auth.DevUser = "tim"
	}
	if c.Auth.DevAuthID == 0 {
		c.Auth.DevAuthID = 1
	}
	if c.Git.Binary == "" {
		c.Git.Binary = "git"
	}
	if c.Git.DefaultBranch == "" {
		c.Git.DefaultBranch = "main"
	}
	if c.SSH.Listen == "" {
		c.SSH.Listen = "0.0.0.0:2222"
	}
	if c.CI.Docker == "" {
		c.CI.Docker = "docker"
	}
	if c.CI.Concurrency <= 0 {
		c.CI.Concurrency = 1
	}
	if c.CI.Network == "" {
		c.CI.Network = "bridge"
	}
	if c.CI.TimeoutSec <= 0 {
		c.CI.TimeoutSec = 1800
	}
	c.Auth.BaseURL = strings.TrimRight(c.Auth.BaseURL, "/")
	c.BaseURL = strings.TrimRight(c.BaseURL, "/")
}

// Validate keurt een configuratie goed of af.
func (c Config) Validate() error {
	if c.BaseURL == "" {
		return fmt.Errorf("base_url ontbreekt")
	}
	u, err := url.Parse(c.BaseURL)
	if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
		return fmt.Errorf("base_url moet een absolute http(s)-URL zijn")
	}
	if c.StoragePath == "" {
		return fmt.Errorf("storage_path ontbreekt")
	}
	if !strings.HasPrefix(c.Auth.RedirectPath, "/") {
		return fmt.Errorf("auth.redirect_path moet met / beginnen")
	}
	switch c.Auth.Mode {
	case "oauth":
		if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
			return fmt.Errorf("oauth vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
		}
		if c.Auth.BaseURL == "" {
			return fmt.Errorf("auth.base_url ontbreekt")
		}
	case "dev":
		if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
			return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
		}
	default:
		return fmt.Errorf("auth.mode moet oauth of dev zijn")
	}
	return nil
}

// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
func (c Config) RedirectURI() string {
	return c.BaseURL + c.Auth.RedirectPath
}

// Example is een startconfiguratie voor de mini-PC.
func Example() string {
	return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml.
base_url: https://git.timfalken.com
listen: 127.0.0.1:8080
# De 4 TB-schijf. De database, repositories, artifacts en releases staan hier.
storage_path: /mnt/storage/bluegit
behind_proxy: true

auth:
  mode: oauth
  base_url: https://auth.timfalken.com
  # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
  client_id: git.timfalken.com
  # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
  client_secret: ""
  client_secret_file: /etc/bluegit/client_secret
  redirect_path: /auth/callback
  user_agent: BlueGitAccountClient/0.1

git:
  binary: git
  default_branch: main

ssh:
  enabled: true
  listen: 0.0.0.0:2222

ci:
  enabled: true
  docker_binary: docker
  concurrency: 1
  network: bridge
  timeout_seconds: 1800
`
}
