package permission

import (
	"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"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Del(c *gin.Context) {
	var request = types.PermissionRequest{}

	// 解析JSON请求
	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 err := impl.DBService.Transaction(func(tx *gorm.DB) error {
		// 删除权限
		if err = tx.Delete(&models.MgtPermission{}, request.ID).Error; err != nil {
			printer.Error("删除权限异常: %v", err)
			return err
		}

		// 删除用户权限关联
		if err = tx.Where("pmn_id = ?", request.ID).Delete(&models.MgtLinkUserPmn{}).Error; err != nil {
			printer.Error("删除用户权限关联异常: %v", err)
			return err
		}

		// 删除角色权限关联
		if err = tx.Where("pmn_id = ?", request.ID).Delete(&models.MgtLinkRolePmn{}).Error; err != nil {
			printer.Error("删除角色权限关联异常: %v", err)
			return err
		}

		// 删除部门权限关联
		if err = tx.Where("pmn_id = ?", request.ID).Delete(&models.MgtLinkDptPmn{}).Error; err != nil {
			printer.Error("删除部门权限关联异常: %v", err)
			return err
		}

		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("权限删除成功: ID=%d", request.ID)
	infra.Response.Success(c, types.IdResp{Id: request.ID})
}
