package tasks

import (
	"fmt"
	"testing"

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

func TestAssigneeOnlySeesExplicitlySharedObjects(t *testing.T) {
	database := newTestDB(t)
	assigneeID := uint(2)
	task := models.SenlinAgentTask{ProjectID: 1, CreatedBy: 1, AssigneeID: &assigneeID, Title: "处理合同"}
	note := models.SenlinAgentNote{ProjectID: 1, CreatedBy: 1, Title: "合同背景", Markdown: "只在共享后可见"}
	require.NoError(t, database.Create(&task).Error)
	require.NoError(t, database.Create(&note).Error)
	service := NewService()

	before, err := service.VisibleLinkedObjects(task.ID, assigneeID)
	require.NoError(t, err)
	require.Empty(t, before)

	require.NoError(t, service.ShareObject(task.ID, "note", note.ID))
	after, err := service.VisibleLinkedObjects(task.ID, assigneeID)
	require.NoError(t, err)
	require.Len(t, after, 1)
	require.Equal(t, "note", after[0].ObjectType)
	require.Equal(t, note.ID, after[0].ObjectID)
}

func TestShareObjectRejectsUnsupportedType(t *testing.T) {
	newTestDB(t)
	service := NewService()

	err := service.ShareObject(1, "ai_session", 9)

	require.ErrorContains(t, err, "unsupported shared object type")
}

func TestShareObjectRejectsObjectFromAnotherProject(t *testing.T) {
	database := newTestDB(t)
	task := models.SenlinAgentTask{ProjectID: 1, CreatedBy: 1, Title: "Review"}
	note := models.SenlinAgentNote{ProjectID: 2, CreatedBy: 1, Title: "Other project", Markdown: "Private context"}
	require.NoError(t, database.Create(&task).Error)
	require.NoError(t, database.Create(&note).Error)
	service := NewService()

	err := service.ShareObject(task.ID, "note", note.ID)

	require.ErrorContains(t, err, "shared object not found in task project")
}

func TestAssignRecordsProjectEvent(t *testing.T) {
	database := newTestDB(t)
	task := models.SenlinAgentTask{ProjectID: 7, CreatedBy: 1, Title: "安排评审"}
	require.NoError(t, database.Create(&task).Error)
	service := NewService()

	require.NoError(t, service.Assign(task.ID, 2))

	var event models.SenlinAgentProjectEvent
	require.NoError(t, database.Where("project_id = ? AND entity_type = ? AND entity_id = ?", 7, "task", task.ID).First(&event).Error)
	require.Equal(t, "task_assigned", event.EventType)
}

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
}
