package persistence

import (
	"strings"
	"testing"

	"github.com/nexuscrm/backend/internal/domain/schema"
	"github.com/stretchr/testify/assert"
)

func TestGenerateUniqueIndexName(t *testing.T) {
	// Case 1: Short Name (should be preserved exactly)
	shortTable := "table"
	shortCol := "col"
	expectedShort := "uniq_table_col"
	assert.Equal(t, expectedShort, schema.GenerateUniqueIndexName(shortTable, shortCol))

	// Case 2: Long Name (should be hashed)
	longTable := strings.Repeat("t", 40)
	longCol := strings.Repeat("c", 40)
	// combined "uniq_..." would be > 80 chars.
	result := schema.GenerateUniqueIndexName(longTable, longCol)

	assert.LessOrEqual(t, len(result), 64, "Generated name must be <= 64 chars")
	assert.True(t, strings.HasPrefix(result, "uniq_"), "Must start with uniq_ prefix")
	// MD5 hash is 32 hex chars. uniq_ is 5 chars. Total 37.
	assert.Len(t, result, 37, "Hashed name should be 37 characters (uniq_ + md5)")

	// Case 3: Deterministic & Collision Resistance
	// Same input -> Same output
	assert.Equal(t, result, schema.GenerateUniqueIndexName(longTable, longCol))

	// Different input -> Different output
	res2 := schema.GenerateUniqueIndexName(longTable, longCol+"x")
	assert.NotEqual(t, result, res2, "Different inputs should produce different hashes")
}
