package database

import (
	"strings"
	"testing"
)

// ── Additional Test Seed Helpers (v0.15.0) ──

// SeedTestMessage creates a single message in a channel and returns the message ID.
func SeedTestMessage(t *testing.T, channelID, parentID, role, content string) string {
	t.Helper()
	var id string
	var parentPtr *string
	if parentID != "" {
		parentPtr = &parentID
	}
	err := DB.QueryRow(`
		INSERT INTO messages (channel_id, parent_id, role, content, sibling_index)
		VALUES ($1, $2, $3, $4, 0)
		RETURNING id
	`, channelID, parentPtr, role, content).Scan(&id)
	if err != nil {
		t.Fatalf("SeedTestMessage: %v", err)
	}
	return id
}

// SeedTestMessages creates a linear chain of alternating user/assistant messages.
// Returns all message IDs in order. The first message has no parent.
func SeedTestMessages(t *testing.T, channelID string, count int, contentSize int) []string {
	t.Helper()
	content := strings.Repeat("x", contentSize)
	ids := make([]string, 0, count)

	parentID := ""
	for i := 0; i < count; i++ {
		role := "user"
		if i%2 == 1 {
			role = "assistant"
		}
		id := SeedTestMessage(t, channelID, parentID, role, content)
		ids = append(ids, id)
		parentID = id
	}

	return ids
}

// SeedTestCursor sets the active leaf for a user in a channel.
func SeedTestCursor(t *testing.T, channelID, userID, leafID string) {
	t.Helper()
	_, err := DB.Exec(`
		INSERT INTO channel_cursors (channel_id, user_id, active_leaf_id)
		VALUES ($1, $2, $3)
		ON CONFLICT (channel_id, user_id)
		DO UPDATE SET active_leaf_id = $3, updated_at = NOW()
	`, channelID, userID, leafID)
	if err != nil {
		t.Fatalf("SeedTestCursor: %v", err)
	}
}
