//
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package user

import (
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/libs/crypto"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
)

// CreateRequest 创建用户请求
type CreateRequest struct {
	Username string `json:"username" src:"json" desc:"用户名"`
	Password string `json:"password" src:"json" desc:"密码"`
	Email    string `json:"email,omitempty" src:"json" desc:"邮箱"`
	Phone    string `json:"phone,omitempty" src:"json" desc:"手机号"`
	Nickname string `json:"nickname,omitempty" src:"json" desc:"昵称"`
	Status   int    `json:"status" src:"json" default:"1" desc:"用户状态"`
}

// create 创建用户
func create(x *vigo.X, req *CreateRequest) (*models.User, error) {
	// 检查用户名是否已存在
	var count int64
	cfg.DB().Model(&models.User{}).Where("username = ?", req.Username).Count(&count)
	if count > 0 {
		return nil, vigo.ErrInvalidArg.WithString("username already exists")
	}

	// 检查邮箱是否已存在
	if req.Email != "" {
		cfg.DB().Model(&models.User{}).Where("email = ?", req.Email).Count(&count)
		if count > 0 {
			return nil, vigo.ErrInvalidArg.WithString("email already exists")
		}
	}

	// 哈希密码
	hashedPassword, err := crypto.HashPassword(req.Password, 12)
	if err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	// 创建用户
	var email *string
	if req.Email != "" {
		email = &req.Email
	}
	var phone *string
	if req.Phone != "" {
		phone = &req.Phone
	}

	user := &models.User{
		Username: req.Username,
		Password: hashedPassword,
		Email:    email,
		Phone:    phone,
		Nickname: req.Nickname,
		Status:   req.Status,
	}

	if user.Nickname == "" {
		user.Nickname = user.Username
	}

	if err := cfg.DB().Create(user).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	// 授予默认角色 "user"
	if err := cfg.Auth.GrantRole(x.Context(), user.ID, "user"); err != nil {
		// 记录错误但允许流程继续
	}

	return user, nil
}
