package initdb

import (
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"senlinai-agent/backend/internal/models"
)

const (
	rootUsername = "root"
	rootPassword = "123456"
	rootRole     = "root"
)

// InitUser creates the default root account when the user table is empty.
func InitUser(database *gorm.DB) error {
	var count int64
	if err := database.Model(&models.SaUser{}).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return nil
	}

	passwordHash, err := bcrypt.GenerateFromPassword([]byte(rootPassword), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	return database.Create(&models.SaUser{
		Email:        rootUsername,
		DisplayName:  rootUsername,
		PasswordHash: string(passwordHash),
		Role:         rootRole,
	}).Error
}
