package app

import (
	"path/filepath"
	"testing"

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

func setupWorkspaceService(t *testing.T) *WorkspaceService {
	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 NewWorkspaceService(settings.NewSettingsService(d))
}

func TestSaveAndLoadWorkspace(t *testing.T) {
	svc := setupWorkspaceService(t)
	snapshot := &WorkspaceSnapshot{
		Tabs: []WorkspaceTab{
			{ConnectionID: 1, Protocol: "ssh", Position: 0},
			{ConnectionID: 5, Protocol: "rdp", Position: 1},
		},
		SidebarWidth: 240,
		SidebarMode:  "connections",
		ActiveTab:    0,
	}
	if err := svc.Save(snapshot); err != nil {
		t.Fatal(err)
	}
	loaded, err := svc.Load()
	if err != nil {
		t.Fatal(err)
	}
	if len(loaded.Tabs) != 2 {
		t.Errorf("len(Tabs) = %d, want 2", len(loaded.Tabs))
	}
	if loaded.SidebarWidth != 240 {
		t.Errorf("SidebarWidth = %d, want 240", loaded.SidebarWidth)
	}
}

func TestLoadEmptyWorkspace(t *testing.T) {
	svc := setupWorkspaceService(t)
	loaded, err := svc.Load()
	if err != nil {
		t.Fatal(err)
	}
	if loaded != nil {
		t.Error("should return nil for empty workspace")
	}
}

func TestCleanShutdownFlag(t *testing.T) {
	svc := setupWorkspaceService(t)
	if svc.WasCleanShutdown() {
		t.Error("should not be clean initially")
	}
	svc.MarkCleanShutdown()
	if !svc.WasCleanShutdown() {
		t.Error("should be clean after marking")
	}
	svc.ClearCleanShutdown()
	if svc.WasCleanShutdown() {
		t.Error("should not be clean after clearing")
	}
}
