package config

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

func TestGenerateAndLoadRoundTrip(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "settings.ini")

	cfg, err := Load(path)
	if err != nil {
		t.Fatalf("Load (generate): %v", err)
	}
	if _, err := os.Stat(path); err != nil {
		t.Fatalf("settings.ini was not written: %v", err)
	}
	if got := cfg.Section("Server").Key("SMTP_PORT").String(); got != "25" {
		t.Errorf("SMTP_PORT = %q, want 25", got)
	}
	if got := cfg.Section("Attachments").Key("attachments_path").String(); got == "" {
		t.Error("Attachments.attachments_path default is missing (the approved bug fix)")
	}

	// Load again against the now-existing file — must not regenerate/overwrite.
	cfg2, err := Load(path)
	if err != nil {
		t.Fatalf("Load (existing): %v", err)
	}
	if got := cfg2.Section("Server").Key("SMTP_PORT").String(); got != "25" {
		t.Errorf("second Load: SMTP_PORT = %q, want 25", got)
	}
}

func TestAbsoluteSQLitePath(t *testing.T) {
	cases := []struct{ url, root, want string }{
		{"sqlite:///server_data/db.sqlite", "/app", "/app/server_data/db.sqlite"},
		{"sqlite:////abs/db.sqlite", "/app", "/abs/db.sqlite"},
		{"mysql://x", "/app", "mysql://x"},
	}
	for _, c := range cases {
		if got := AbsoluteSQLitePath(c.url, c.root); got != c.want {
			t.Errorf("AbsoluteSQLitePath(%q, %q) = %q, want %q", c.url, c.root, got, c.want)
		}
	}
}
