package seed

import (
	"fmt"
	"testing"

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

func TestDemoSeedCreatesFrontendWorkspaceData(t *testing.T) {
	database := newTestDB(t)

	result, err := Demo(database, DemoOptions{
		Email:       "demo@senlin.ai",
		DisplayName: "演示用户",
		Password:    "password123",
	})

	require.NoError(t, err)
	require.Equal(t, "demo@senlin.ai", result.User.Email)
	require.Len(t, result.Projects, 4)

	token, err := auth.NewService("test-secret").Login("demo@senlin.ai", "password123")
	require.NoError(t, err)
	require.NotEmpty(t, token)

	workspace, err := projects.NewService().Workspace(result.User.ID, result.Projects[0].Identity)
	require.NoError(t, err)
	require.Equal(t, "项目 A1", workspace.Project.Name)
	require.GreaterOrEqual(t, len(workspace.Inbox), 4)
	require.GreaterOrEqual(t, len(workspace.Tasks), 3)
	require.GreaterOrEqual(t, len(workspace.AISessions), 4)
	require.GreaterOrEqual(t, len(workspace.NotesSources), 3)
	require.GreaterOrEqual(t, len(workspace.CronPlans), 3)
	for _, plan := range workspace.CronPlans {
		require.Empty(t, plan.LastResult, "演示数据不得声称计划已执行")
	}
	require.Len(t, workspace.Channels, 8)
}

func TestDemoSeedIsIdempotent(t *testing.T) {
	database := newTestDB(t)

	first, err := Demo(database, DemoOptions{Email: "demo@senlin.ai", DisplayName: "演示用户", Password: "password123"})
	require.NoError(t, err)
	second, err := Demo(database, DemoOptions{Email: "demo@senlin.ai", DisplayName: "演示用户", Password: "password123"})
	require.NoError(t, err)

	require.Equal(t, first.User.ID, second.User.ID)
	require.Len(t, second.Projects, 4)
	var userCount int64
	require.NoError(t, database.Model(&models.SenlinAgentUser{}).Where("email = ?", "demo@senlin.ai").Count(&userCount).Error)
	require.Equal(t, int64(1), userCount)
}

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
}
