package inbox

import (
	"fmt"
	"testing"

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

func TestAnalyzeReturnsSuggestionsWithoutCreatingObjects(t *testing.T) {
	database := newTestDB(t)
	service := NewService(StaticAnalyzer{
		Suggestions: []Suggestion{{Kind: "task", Title: "跟进报价", Body: "联系客户确认报价"}},
	})
	item, err := service.Capture(CaptureInput{ProjectID: 1, UserID: 1, SourceType: "text", Body: "需要跟进报价"})
	require.NoError(t, err)

	suggestions, err := service.Analyze(item.ID, 1)

	require.NoError(t, err)
	require.Len(t, suggestions, 1)
	var count int64
	require.NoError(t, database.Model(&models.SenlinAgentTask{}).Count(&count).Error)
	require.Equal(t, int64(0), count)
}

func TestConfirmCreatesSelectedObjectsAndKeepsInboxItem(t *testing.T) {
	database := newTestDB(t)
	service := NewService(StaticAnalyzer{
		Suggestions: []Suggestion{{Kind: "task", Title: "跟进报价", Body: "联系客户确认报价"}},
	})
	item, err := service.Capture(CaptureInput{ProjectID: 1, UserID: 1, SourceType: "text", Body: "需要跟进报价"})
	require.NoError(t, err)

	suggestions, err := service.Analyze(item.ID, 1)
	require.NoError(t, err)
	err = service.Confirm(item.ID, suggestions)

	require.NoError(t, err)
	var tasks []models.SenlinAgentTask
	require.NoError(t, database.Find(&tasks).Error)
	require.Len(t, tasks, 1)
	require.Equal(t, "跟进报价", tasks[0].Title)
	require.NotNil(t, tasks[0].SourceInboxItemID)
	require.Equal(t, item.ID, *tasks[0].SourceInboxItemID)
	var reloaded models.SenlinAgentInboxItem
	require.NoError(t, database.First(&reloaded, item.ID).Error)
	require.Equal(t, "processed", reloaded.Status)
}

func newTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, models.AutoMigrate(database))
	models.DBService = database
	return database
}
