package role

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

func Create(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.Name == "" {
		printer.Error("role name is required: name=%s", request.Name)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

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

	var dataModel = models.MgtRole{
		Description: request.Description,
		Name:        request.Name,
		Std_IICUDS:  coreTypes.Std_IICUDS{Identity: coreutils.UUID(), Status: 1},
	}
	if err = impl.DBService.Model(&models.MgtRole{}).Create(&dataModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

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