package main

import (
	"os/exec"
	"testing"
	"time"
)

func TestNewPool(t *testing.T) {
	p := NewPool()
	if p == nil {
		t.Fatal("NewPool returned nil")
	}
}

func TestPool_Get_NoSession(t *testing.T) {
	p := NewPool()
	s := p.Get("nonexistent")
	if s != nil {
		t.Fatal("Get on empty pool should return nil")
	}
}

func TestPool_IsAlive_NoSession(t *testing.T) {
	p := NewPool()
	if p.IsAlive("nonexistent") {
		t.Fatal("IsAlive on empty pool should return false")
	}
}

func TestPool_CloseAll_Empty(t *testing.T) {
	p := NewPool()
	p.CloseAll() // must not panic
}

func TestPool_Attach_Real(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping integration test in short mode")
	}

	name := "test-muxterm"

	// Ensure the tmux session exists.
	exec.Command("tmux", "kill-session", "-t", name).Run()
	cmd := exec.Command("tmux", "new-session", "-d", "-s", name, "-x", "80", "-y", "24")
	if err := cmd.Run(); err != nil {
		t.Fatalf("failed to create tmux session %q: %v", name, err)
	}
	defer exec.Command("tmux", "kill-session", "-t", name).Run()

	p := NewPool()
	defer p.CloseAll()

	// Attach
	sess, err := p.Attach(name, 80, 24)
	if err != nil {
		t.Fatalf("Attach failed: %v", err)
	}
	if sess == nil {
		t.Fatal("Attach returned nil session")
	}
	if sess.PTY == nil {
		t.Fatal("Session PTY is nil")
	}

	// IsAlive
	if !p.IsAlive(name) {
		t.Fatal("IsAlive should return true after Attach")
	}

	// Resize
	err = p.Resize(name, 120, 40)
	if err != nil {
		t.Fatalf("Resize failed: %v", err)
	}
	resized := p.Get(name)
	if resized.Cols != 120 {
		t.Errorf("After resize Cols = %d, want 120", resized.Cols)
	}
	if resized.Rows != 40 {
		t.Errorf("After resize Rows = %d, want 40", resized.Rows)
	}

	// Cleanup
	p.CloseAll()
	time.Sleep(100 * time.Millisecond)
	if p.IsAlive(name) {
		t.Fatal("IsAlive should return false after CloseAll")
	}
}
