package session

import "testing"

func TestCreateSession(t *testing.T) {
	m := NewManager()
	s, err := m.Create(1, "ssh")
	if err != nil {
		t.Fatalf("Create() error: %v", err)
	}
	if s.ID == "" {
		t.Error("session ID should not be empty")
	}
	if s.State != StateConnecting {
		t.Errorf("State = %q, want %q", s.State, StateConnecting)
	}
}

func TestMaxSessions(t *testing.T) {
	m := NewManager()
	for i := 0; i < MaxSessions; i++ {
		_, err := m.Create(int64(i), "ssh")
		if err != nil {
			t.Fatalf("Create() error at %d: %v", i, err)
		}
	}
	_, err := m.Create(999, "ssh")
	if err == nil {
		t.Error("Create() should fail at max sessions")
	}
}

func TestDetachReattach(t *testing.T) {
	m := NewManager()
	s, _ := m.Create(1, "ssh")
	m.SetState(s.ID, StateConnected)

	if err := m.Detach(s.ID); err != nil {
		t.Fatalf("Detach() error: %v", err)
	}

	got, _ := m.Get(s.ID)
	if got.State != StateDetached {
		t.Errorf("State = %q, want %q", got.State, StateDetached)
	}

	if err := m.Reattach(s.ID, "window-1"); err != nil {
		t.Fatalf("Reattach() error: %v", err)
	}

	got, _ = m.Get(s.ID)
	if got.State != StateConnected {
		t.Errorf("State = %q, want %q", got.State, StateConnected)
	}
}

func TestRemoveSession(t *testing.T) {
	m := NewManager()
	s, _ := m.Create(1, "ssh")
	m.Remove(s.ID)
	if m.Count() != 0 {
		t.Error("session should have been removed")
	}
}
