package models

import (
	"fmt"
	"testing"

	"github.com/glebarez/sqlite"
	"github.com/stretchr/testify/require"
	"gorm.io/gorm"
)

func TestBeforeCreateAssignsUUIDV7Identity(t *testing.T) {
	database := newIdentityTestDB(t)
	user := SenlinAgentUser{Email: "lead@example.com", DisplayName: "Lead", PasswordHash: "hash"}

	require.NoError(t, database.Create(&user).Error)

	require.NotEmpty(t, user.Identity)
	require.Equal(t, byte('7'), user.Identity[14])
}

func TestBeforeCreateCopiesParentIdentitiesFromNumericIDs(t *testing.T) {
	database := newIdentityTestDB(t)
	user := SenlinAgentUser{Email: "lead@example.com", DisplayName: "Lead", PasswordHash: "hash"}
	require.NoError(t, database.Create(&user).Error)
	project := SenlinAgentProject{OwnerID: user.ID, Name: "Alpha"}
	require.NoError(t, database.Create(&project).Error)
	item := SenlinAgentInboxItem{ProjectID: project.ID, CreatedBy: user.ID, SourceType: "text"}
	require.NoError(t, database.Create(&item).Error)

	task := SenlinAgentTask{ProjectID: project.ID, CreatedBy: user.ID, SourceInboxItemID: &item.ID, Title: "Follow up"}

	require.NoError(t, database.Create(&task).Error)

	require.NotEmpty(t, project.Identity)
	require.Equal(t, user.Identity, project.OwnerIdentity)
	require.Equal(t, project.Identity, task.ProjectIdentity)
	require.Equal(t, user.Identity, task.CreatedByIdentity)
	require.NotNil(t, task.SourceInboxItemIdentity)
	require.Equal(t, item.Identity, *task.SourceInboxItemIdentity)
}

func newIdentityTestDB(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, AutoMigrate(database))
	return database
}
