package initdb

import (
	"testing"

	"github.com/glebarez/sqlite"
	"github.com/stretchr/testify/require"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"senlinai-agent/backend/internal/models"
)

func TestInitUserCreatesRootUserWhenTableIsEmpty(t *testing.T) {
	database := newUserTestDatabase(t)

	require.NoError(t, InitUser(database))

	var users []models.SaUser
	require.NoError(t, database.Find(&users).Error)
	require.Len(t, users, 1)
	require.Equal(t, rootUsername, users[0].Email)
	require.Equal(t, rootUsername, users[0].DisplayName)
	require.Equal(t, rootRole, users[0].Role)
	require.NoError(t, bcrypt.CompareHashAndPassword([]byte(users[0].PasswordHash), []byte(rootPassword)))
}

func TestInitUserDoesNothingWhenTableIsNotEmpty(t *testing.T) {
	database := newUserTestDatabase(t)
	existing := models.SaUser{
		Email:        "existing@example.com",
		DisplayName:  "Existing User",
		PasswordHash: "existing-hash",
		Role:         "user",
	}
	require.NoError(t, database.Create(&existing).Error)

	require.NoError(t, InitUser(database))

	var users []models.SaUser
	require.NoError(t, database.Find(&users).Error)
	require.Len(t, users, 1)
	require.Equal(t, existing.Email, users[0].Email)
}

func newUserTestDatabase(t *testing.T) *gorm.DB {
	t.Helper()

	database, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, database.AutoMigrate(&models.SaUser{}))
	return database
}
