package settings

import (
	"path/filepath"
	"testing"

	"github.com/vstockwell/wraith/internal/db"
)

func setupTestDB(t *testing.T) *SettingsService {
	t.Helper()
	d, err := db.Open(filepath.Join(t.TempDir(), "test.db"))
	if err != nil {
		t.Fatal(err)
	}
	if err := db.Migrate(d); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { d.Close() })
	return NewSettingsService(d)
}

func TestSetAndGet(t *testing.T) {
	s := setupTestDB(t)

	if err := s.Set("theme", "dracula"); err != nil {
		t.Fatalf("Set() error: %v", err)
	}

	val, err := s.Get("theme")
	if err != nil {
		t.Fatalf("Get() error: %v", err)
	}
	if val != "dracula" {
		t.Errorf("Get() = %q, want %q", val, "dracula")
	}
}

func TestGetMissing(t *testing.T) {
	s := setupTestDB(t)

	val, err := s.Get("nonexistent")
	if err != nil {
		t.Fatalf("Get() error: %v", err)
	}
	if val != "" {
		t.Errorf("Get() = %q, want empty string", val)
	}
}

func TestSetOverwrites(t *testing.T) {
	s := setupTestDB(t)

	s.Set("key", "value1")
	s.Set("key", "value2")

	val, _ := s.Get("key")
	if val != "value2" {
		t.Errorf("Get() = %q, want %q", val, "value2")
	}
}

func TestGetWithDefault(t *testing.T) {
	s := setupTestDB(t)

	val := s.GetDefault("missing", "fallback")
	if val != "fallback" {
		t.Errorf("GetDefault() = %q, want %q", val, "fallback")
	}
}
