package application

import (
	"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.ApplicationRequest{}
	)

	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
	}

	appId := request.ID
	var dptIds []uint

	if err := models.DBService.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&models.MgtDepartment{}).Where("app_id = ?", appId).Pluck("id", &dptIds).Error; err != nil {
			printer.Error("查询应用部门异常: %v", err)
			return err
		}
		if len(dptIds) > 0 {
			if err := tx.Where("dpt_id in ?", dptIds).Delete(&models.MgtLinkUserDpt{}).Error; err != nil {
				return err
			}
			if err := tx.Where("dpt_id in ?", dptIds).Delete(&models.MgtLinkDptRole{}).Error; err != nil {
				return err
			}
			if err := tx.Where("dpt_id in ?", dptIds).Delete(&models.MgtLinkDptPmn{}).Error; err != nil {
				return err
			}
			if err := tx.Where("id in ?", dptIds).Delete(&models.MgtDepartment{}).Error; err != nil {
				return err
			}
		}

		if err := tx.Where("app_id = ?", appId).Delete(&models.MgtLinkUserApp{}).Error; err != nil {
			return err
		}
		if err := tx.Where("app_id = ?", appId).Delete(&models.MgtLinkRoleApp{}).Error; err != nil {
			return err
		}
		if err := tx.Where("app_id = ?", appId).Delete(&models.MgtLinkUserPmn{}).Error; err != nil {
			return err
		}
		if err := tx.Where("app_id = ?", appId).Delete(&models.MgtLinkRolePmn{}).Error; err != nil {
			return err
		}
		if err := tx.Where("app_id = ?", appId).Delete(&models.MgtLinkDptPmn{}).Error; err != nil {
			return err
		}
		if err := tx.Where("app_id = ?", appId).Delete(&models.MgtPermission{}).Error; err != nil {
			return err
		}
		if err := tx.Delete(&models.MgtApplication{}, appId).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})
}
