package config

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestPresetConfig(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	docker := filepath.Join(dir, "Dockerfile")
	if err := os.WriteFile(docker, []byte("FROM alpine:3.20\nRUN apk add --no-cache git\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	body := []byte("base_url: https://git.example.test\nauth:\n  mode: oauth\n  client_id: git.example.test\nci:\n  presets:\n    bluegit/node:\n      from: node:22-bookworm\n    team/tools:\n      dockerfile: Dockerfile\n    team/plain:\n      image: alpine:3.20\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.CI.Presets["team/tools"].Dockerfile != docker {
		t.Fatalf("pad %s", cfg.CI.Presets["team/tools"].Dockerfile)
	}
	if cfg.CI.Presets["bluegit/node"].From != "node:22-bookworm" || cfg.CI.Presets["team/plain"].Image != "alpine:3.20" {
		t.Fatalf("%+v", cfg.CI.Presets)
	}
	bad := []byte("base_url: https://git.example.test\nauth:\n  mode: oauth\n  client_id: git.example.test\nci:\n  presets:\n    node:22:\n      image: alpine\n")
	if err := os.WriteFile(path, bad, 0o600); err != nil {
		t.Fatal(err)
	}
	if _, err := Load(path); err == nil {
		t.Fatal("een tag in de aliasnaam hoort te falen")
	}
}

func TestRunnerName(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.example.test\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.Runner.Name != "Steve" {
		t.Fatalf("standaard %q", cfg.Runner.Name)
	}
	body = []byte("base_url: https://git.example.test\nrunner:\n  name: \"  Ada  \"\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	cfg, err = Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.Runner.Name != "Ada" {
		t.Fatalf("naam %q", cfg.Runner.Name)
	}
}

func TestStoragePathOptional(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.example.test\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.StoragePath != "" {
		t.Fatalf("geen standaardpad verwacht, kreeg %q", cfg.StoragePath)
	}
	if cfg.StatePath != "/var/lib/bluegit" {
		t.Fatal(cfg.StatePath)
	}
	if strings.Contains(Example(), "/mnt/storage") {
		t.Fatal("voorbeeldconfiguratie bevat nog een vast schijfpad")
	}
}

func TestDevModeRefusedOnProductionHost(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.timfalken.com\nstorage_path: /mnt/storage/bluegit\nauth:\n  mode: dev\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	_, err := Load(path)
	if err == nil || !strings.Contains(err.Error(), "dev") {
		t.Fatalf("verwacht weigering, kreeg %v", err)
	}
}

func TestOAuthDefaultsUnchanged(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.example.test\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.Auth.Mode != "oauth" || cfg.Auth.BaseURL != "https://auth.timfalken.com" {
		t.Fatalf("%+v", cfg.Auth)
	}
	if cfg.Auth.RedirectPath != "/auth/callback" || cfg.Auth.UserAgent != "BlueGitAccountClient/0.1" {
		t.Fatalf("%+v", cfg.Auth)
	}
	if cfg.Auth.TenantID != "" || cfg.Auth.Issuer != "" {
		t.Fatalf("entra-velden horen leeg: %+v", cfg.Auth)
	}
}

func TestEntraConfig(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte(`base_url: https://git.example.test
auth:
  mode: entra
  tenant_id: 00000000-0000-0000-0000-000000000001
  client_id: 11111111-1111-1111-1111-111111111111
`)
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "entra-geheim")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.Auth.BaseURL != "" {
		t.Fatalf("entra zet geen auth.timfalken-default, kreeg %q", cfg.Auth.BaseURL)
	}
	if cfg.EntraIssuer() != "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0" {
		t.Fatal(cfg.EntraIssuer())
	}
	if cfg.Auth.ClientSecret != "entra-geheim" || cfg.RedirectURI() != "https://git.example.test/auth/callback" {
		t.Fatalf("%+v", cfg.Auth)
	}

	body = []byte(`base_url: https://git.example.test
auth:
  mode: entra
  tenant_id: 00000000-0000-0000-0000-000000000001
  client_id: 11111111-1111-1111-1111-111111111111
  issuer: https://login.test.example/t/v2.0
`)
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	cfg, err = Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.EntraIssuer() != "https://login.test.example/t/v2.0" {
		t.Fatal(cfg.EntraIssuer())
	}
}

func TestEntraValidation(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	cases := []struct {
		body string
		want string
	}{
		{
			body: "base_url: https://git.example.test\nauth:\n  mode: entra\n  client_id: app\n",
			want: "tenant_id",
		},
		{
			body: "base_url: https://git.example.test\nauth:\n  mode: entra\n  tenant_id: t1\n",
			want: "client_id",
		},
		{
			body: "base_url: https://git.example.test\nauth:\n  mode: entra\n  tenant_id: t1\n  client_id: app\n  issuer: niet-een-url\n",
			want: "issuer",
		},
		{
			body: "base_url: https://git.example.test\nauth:\n  mode: entra\n  tenant_id: t1\n  client_id: app\n  issuer: http://login.microsoftonline.com/t/v2.0\n",
			want: "HTTPS",
		},
	}
	for _, tc := range cases {
		if err := os.WriteFile(path, []byte(tc.body), 0o600); err != nil {
			t.Fatal(err)
		}
		_, err := Load(path)
		if err == nil || !strings.Contains(err.Error(), tc.want) {
			t.Fatalf("body %q: verwacht %q, kreeg %v", tc.body, tc.want, err)
		}
	}
	// Zonder geheim:zelfde fouttekst als oauth.
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "")
	body := []byte("base_url: https://git.example.test\nauth:\n  mode: entra\n  tenant_id: t1\n  client_id: app\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	_, err := Load(path)
	if err == nil || !strings.Contains(err.Error(), "clientgeheim") {
		t.Fatalf("verwacht clientgeheim-fout, kreeg %v", err)
	}
}

func TestEntraIssuerHTTPLoopback(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	body := []byte(`base_url: https://git.example.test
auth:
  mode: entra
  tenant_id: t1
  client_id: app
  issuer: http://127.0.0.1:8081/t/v2.0
`)
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.EntraIssuer() != "http://127.0.0.1:8081/t/v2.0" {
		t.Fatal(cfg.EntraIssuer())
	}
}

func TestSecretFromEnv(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.example.test\nstorage_path: " + dir + "\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "uit-de-omgeving")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.Auth.ClientSecret != "uit-de-omgeving" || cfg.Git.DefaultBranch != "master" {
		t.Fatalf("branch %s geheim %s", cfg.Git.DefaultBranch, cfg.Auth.ClientSecret)
	}
	if cfg.RedirectURI() != "https://git.example.test/auth/callback" {
		t.Fatal(cfg.RedirectURI())
	}
	if cfg.SSHPublicHost() != "git.example.test" || cfg.SSHPublicPort() != 2222 {
		t.Fatalf("ssh %s:%d", cfg.SSHPublicHost(), cfg.SSHPublicPort())
	}
	if cfg.CloneSSH("tim/demo") != "" {
		t.Fatal("ssh staat uit, dus geen clone-URL")
	}
}

func TestPublicSSHAndTrustedProxy(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte(`base_url: https://git.timfalken.com
storage_path: ` + dir + `
listen: 0.0.0.0:8080
trusted_proxies: ["10.0.0.2", "192.168.0.0/16"]
auth:
  mode: oauth
  client_id: git.timfalken.com
ssh:
  enabled: true
  listen: 0.0.0.0:2222
  public_host: git.timfalken.com
  public_port: 22
`)
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.CloneSSH("tim/demo") != "git@git.timfalken.com:tim/demo.git" {
		t.Fatal(cfg.CloneSSH("tim/demo"))
	}
	if cfg.ProxySet() == nil || cfg.Listen != "0.0.0.0:8080" {
		t.Fatalf("%+v", cfg)
	}
}

func TestBehindProxyFlagRejected(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.example.test\nstorage_path: " + dir + "\nbehind_proxy: true\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	_, err := Load(path)
	if err == nil || !strings.Contains(err.Error(), "trusted_proxies") {
		t.Fatalf("verwacht weigering van behind_proxy, kreeg %v", err)
	}
}

func TestBadProxyRejected(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yml")
	body := []byte("base_url: https://git.example.test\nstorage_path: " + dir + "\ntrusted_proxies: [ingress.local]\nauth:\n  mode: oauth\n  client_id: git.example.test\n")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	t.Setenv("BLUEGIT_AUTH_CLIENT_SECRET", "geheim")
	_, err := Load(path)
	if err == nil || !strings.Contains(err.Error(), "trusted_proxies") {
		t.Fatalf("verwacht weigering, kreeg %v", err)
	}
	body = []byte("base_url: https://git.example.test\nstorage_path: " + dir + "\nauth:\n  mode: oauth\n  client_id: git.example.test\nssh:\n  enabled: true\n  public_host: git.example.test:22\n")
	path = filepath.Join(dir, "port.yml")
	if err := os.WriteFile(path, body, 0o600); err != nil {
		t.Fatal(err)
	}
	_, err = Load(path)
	if err == nil || !strings.Contains(err.Error(), "public_host") {
		t.Fatalf("verwacht weigering van een poort in de host, kreeg %v", err)
	}
}

func TestCloneSSHForms(t *testing.T) {
	c := Config{SSH: SSH{Enabled: true, PublicHost: "git.example.test", PublicPort: 22}}
	if got := c.CloneSSH("tim/demo"); got != "git@git.example.test:tim/demo.git" {
		t.Fatal(got)
	}
	c.SSH.PublicPort = 2222
	if got := c.CloneSSH("tim/demo"); got != "ssh://git@git.example.test:2222/tim/demo.git" {
		t.Fatal(got)
	}
	c.SSH.PublicHost, c.SSH.PublicPort = "::1", 22
	if got := c.CloneSSH("tim/demo"); got != "git@[::1]:tim/demo.git" {
		t.Fatal(got)
	}
}

func TestParseMaintenanceInterval(t *testing.T) {
	cases := []struct {
		in      string
		want    time.Duration
		enabled bool
		fail    bool
	}{
		{"", 24 * time.Hour, true, false},
		{"24h", 24 * time.Hour, true, false},
		{"168h", 7 * 24 * time.Hour, true, false},
		{"7d", 7 * 24 * time.Hour, true, false},
		{"off", 0, false, false},
		{"0", 0, false, false},
		{"niet-geldig", 0, false, true},
	}
	for _, c := range cases {
		d, on, err := ParseMaintenanceInterval(c.in)
		if c.fail {
			if err == nil {
				t.Fatalf("%q: verwacht een fout", c.in)
			}
			continue
		}
		if err != nil || d != c.want || on != c.enabled {
			t.Fatalf("%q: got %v %v %v, wil %v %v nil", c.in, d, on, err, c.want, c.enabled)
		}
	}
}

func TestLoadRejectsBadMaintenanceInterval(t *testing.T) {
	dir := t.TempDir()
	path := dir + "/bluegit.yml"
	body := []byte("base_url: https://git.example.test\nstorage_path: " + dir + "\nauth:\n  mode: dev\ngit:\n  maintenance_interval: kapot\n")
	if err := os.WriteFile(path, body, 0o644); err != nil {
		t.Fatal(err)
	}
	if _, err := Load(path); err == nil {
		t.Fatal("verwacht een fout bij ongeldig maintenance_interval")
	}
}
