//go:build integration

package search

import (
	"fmt"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"senlinai-agent/backend/internal/models"
)

func TestPostgresSearchMatchesChinesePartialKeywords(t *testing.T) {
	database := newPostgresSearchTestDB(t)
	owner := createSearchUser(t, database, "postgres-search-owner@example.com")
	project := models.SenlinAgentProject{OwnerID: owner.ID, Name: "中文回调平台", Identifier: "PG-CALLBACK"}
	require.NoError(t, database.Create(&project).Error)
	require.NoError(t, database.Create(&models.SenlinAgentTask{ProjectID: project.ID, CreatedBy: owner.ID, Title: "回调任务", Status: "open"}).Error)
	require.NoError(t, database.Create(&models.SenlinAgentNote{ProjectID: project.ID, CreatedBy: owner.ID, Title: "说明", Markdown: "回调验签流程"}).Error)

	results, err := NewService(database).Search(owner.ID, "回调")

	require.NoError(t, err)
	require.Len(t, results, 3)
}

func TestPostgresSearchKeepsAssignmentAndExplicitShareBoundaries(t *testing.T) {
	database := newPostgresSearchTestDB(t)
	owner := createSearchUser(t, database, "postgres-privacy-owner@example.com")
	viewer := createSearchUser(t, database, "postgres-privacy-viewer@example.com")
	project := models.SenlinAgentProject{OwnerID: owner.ID, Name: "保密项目", Identifier: "PG-PRIVATE"}
	require.NoError(t, database.Create(&project).Error)
	assigned := models.SenlinAgentTask{ProjectID: project.ID, CreatedBy: owner.ID, AssigneeID: &viewer.ID, Title: "边界词已指派", Status: "open"}
	require.NoError(t, database.Create(&assigned).Error)
	require.NoError(t, database.Create(&models.SenlinAgentTask{ProjectID: project.ID, CreatedBy: owner.ID, Title: "边界词私有任务", Status: "open"}).Error)
	sharedNote := models.SenlinAgentNote{ProjectID: project.ID, CreatedBy: owner.ID, Title: "边界词共享笔记"}
	require.NoError(t, database.Create(&sharedNote).Error)
	require.NoError(t, database.Create(&models.SenlinAgentNote{ProjectID: project.ID, CreatedBy: owner.ID, Title: "边界词私有笔记"}).Error)
	require.NoError(t, database.Create(&models.SenlinAgentTaskShare{TaskID: assigned.ID, ObjectType: "note", ObjectID: sharedNote.ID}).Error)

	results, err := NewService(database).Search(viewer.ID, "边界词")

	require.NoError(t, err)
	require.Len(t, results, 2)
	require.ElementsMatch(t, []string{assigned.Identity, sharedNote.Identity}, []string{results[0].ID, results[1].ID})
}

func TestPostgresSearchUsesStableFairLimitAndRuneBoundedSnippets(t *testing.T) {
	database := newPostgresSearchTestDB(t)
	owner := createSearchUser(t, database, "postgres-search-order@example.com")
	baseTime := time.Date(2026, time.July, 21, 12, 0, 0, 0, time.UTC)
	for index := 0; index < 60; index++ {
		project := models.SenlinAgentProject{
			Identity:   fmt.Sprintf("00000000-0000-7001-8000-%012d", index),
			OwnerID:    owner.ID,
			Name:       fmt.Sprintf("稳定排序项目 %02d", index),
			Identifier: fmt.Sprintf("PG-SORT-%02d", index),
			UpdatedAt:  baseTime.Add(time.Duration(index) * time.Minute),
		}
		require.NoError(t, database.Create(&project).Error)
		require.NoError(t, database.Create(&models.SenlinAgentTask{
			Identity:  fmt.Sprintf("00000000-0000-7002-8000-%012d", index),
			ProjectID: project.ID,
			CreatedBy: owner.ID,
			Title:     fmt.Sprintf("稳定排序任务 %02d", index),
			Status:    "open",
			UpdatedAt: baseTime.Add(time.Duration(index) * time.Minute),
		}).Error)
		require.NoError(t, database.Create(&models.SenlinAgentNote{
			Identity:  fmt.Sprintf("00000000-0000-7003-8000-%012d", index),
			ProjectID: project.ID,
			CreatedBy: owner.ID,
			Title:     fmt.Sprintf("稳定排序笔记 %02d", index),
			Markdown:  strings.Repeat("森", 300) + "尾",
			UpdatedAt: baseTime.Add(time.Duration(index) * time.Minute),
		}).Error)
	}

	service := NewService(database)
	results, err := service.Search(owner.ID, "稳定排序")
	require.NoError(t, err)
	require.Len(t, results, maxSearchResults)
	require.Equal(t,
		[]string{"project", "task", "note", "project", "task", "note", "project", "task", "note"},
		resultTypes(results[:9]),
	)
	require.Equal(t, "00000000-0000-7001-8000-000000000059", results[0].ID)
	require.Equal(t, "00000000-0000-7002-8000-000000000059", results[1].ID)
	require.Equal(t, "00000000-0000-7003-8000-000000000059", results[2].ID)
	counts := map[string]int{}
	for _, result := range results {
		counts[result.Type]++
	}
	require.Equal(t, map[string]int{"project": 17, "task": 17, "note": 16}, counts)

	again, err := service.Search(owner.ID, "稳定排序")
	require.NoError(t, err)
	require.Equal(t, results, again)

	noteResults, err := service.Search(owner.ID, "森")
	require.NoError(t, err)
	require.NotEmpty(t, noteResults)
	require.Len(t, []rune(noteResults[0].Snippet), 240)
	require.NotContains(t, noteResults[0].Snippet, "尾")
}

func newPostgresSearchTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	dsn := os.Getenv("TEST_DATABASE_URL")
	require.NotEmpty(t, dsn, "TEST_DATABASE_URL is required for integration tests and must point to an isolated database")
	database, err := gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true})
	require.NoError(t, err)
	transaction := database.Begin()
	require.NoError(t, transaction.Error)
	t.Cleanup(func() { transaction.Rollback() })
	require.NoError(t, models.AutoMigrate(transaction))
	return transaction
}
