package role

import (
	"errors"

	"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/printer"
	coreTypes "git.apinb.com/bsm-sdk/core/types"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Midify(c *gin.Context) {
	var (
		request = types.RoleReq{}
		data    = models.MgtRole{}
	)

	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.ID == 0 {
		printer.Error("更新角色参数异常: ID不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Name != "" {
		db := models.DBService.Model(&models.MgtRole{})
		if err = db.Where("name = ? and id<> ?", request.Name, request.ID).First(&data).Error; err != nil {
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
		}
		if data.ID != 0 {
			printer.Info("角色名称已存在: name=%s", request.Name)
			infra.Response.Error(c, errcode.ErrAlreadyExists)
			return
		}
	}

	var roleModel = models.MgtRole{
		Name:        request.Name,
		Description: request.Description,
		Std_IICUDS:  coreTypes.Std_IICUDS{Status: request.Status},
	}
	if err := models.DBService.Model(&models.MgtRole{}).Where("id = ?", request.ID).Updates(&roleModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("角色更新成功: ID=%d", request.ID)
	infra.Response.Success(c, types.IdResp{Id: request.ID, Identity: roleModel.Identity})
}
