package user

import (
	"errors"

	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/middleware"
	"git.apinb.com/bsm-sdk/core/printer"
	coreTypes "git.apinb.com/bsm-sdk/core/types"
	coreutils "git.apinb.com/bsm-sdk/core/utils"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func Create(c *gin.Context) {
	var (
		request  = types.UserRequest{}
		data     = models.MgtUser{}
		linkData = models.MgtApplication{}
	)
	_, err := middleware.ParseAuth(c)
	if err != nil {
		infra.Response.Error(c, errcode.ErrTokenAuthNotFound)
		return
	}

	err = c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Account == "" || request.Phone == "" || request.PassWord == "" {
		printer.Error("account, phone and password are required: account=%s, phone=%s", request.Account, request.Phone)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	db := impl.DBService.Model(&models.MgtUser{})
	if err = db.Where("phone = ? or account = ?", request.Phone, request.Account).First(&data).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		var deletedData models.MgtUser
		if err = impl.DBService.Unscoped().Where("phone = ?", request.Phone).First(&deletedData).Error; err == nil {
			if err = impl.DBService.Unscoped().Delete(&deletedData).Error; err != nil {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
			printer.Info("user deleted: id=%d, phone=%s", deletedData.ID, deletedData.Phone)
		}
		if request.Phone != request.Account {
			if err = impl.DBService.Unscoped().Where("account = ?", request.Account).First(&deletedData).Error; err == nil {
				if err = impl.DBService.Unscoped().Delete(&deletedData).Error; err != nil {
					infra.Response.Error(c, errcode.ErrDB)
					return
				}
			}
		}
	} else {
		infra.Response.Error(c, errcode.ErrAlreadyExists)
		return
	}

	if request.Workspace == "" {
		request.Workspace = "def"
	}
	if err = impl.DBService.Model(&models.MgtApplication{}).Where("workspace = ?", request.Workspace).First(&linkData).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	salt := coreutils.UUID()
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(request.PassWord+salt), bcrypt.DefaultCost)
	if err != nil {
		infra.Response.Error(c, errcode.ErrInternal)
		return
	}

	var userModel = models.MgtUser{
		Account:    request.Account,
		Name:       request.Name,
		Password:   string(hashedPassword),
		Phone:      request.Phone,
		Email:      request.Email,
		Avatar:     request.Avatar,
		Salt:       salt,
		Std_IICUDS: coreTypes.Std_IICUDS{Identity: coreutils.UUID(), Status: 1},
	}

	if err = impl.DBService.Transaction(func(tx *gorm.DB) error {
		if err = tx.Model(&models.MgtUser{}).Create(&userModel).Error; err != nil {
			return err
		}
		userLink := models.MgtLinkUserApp{
			AppId:  linkData.ID,
			UserId: userModel.ID,
		}
		if err = tx.Model(&models.MgtLinkUserApp{}).Create(&userLink).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	infra.Response.Success(c, types.IdResp{Id: userModel.ID, Identity: userModel.Identity})
}
