package department

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

func getDepartmentIdsRecursive(db *gorm.DB, appId uint, rootDeptId uint) ([]uint, error) {
	var allDepts []models.MgtDepartment
	if err := db.Select("id", "parent_id").Where("app_id = ?", appId).Find(&allDepts).Error; err != nil {
		return nil, err
	}
	childrenMap := make(map[uint][]uint, len(allDepts))
	for _, dept := range allDepts {
		if dept.ParentID > 0 {
			childrenMap[dept.ParentID] = append(childrenMap[dept.ParentID], dept.ID)
		}
	}
	result := make([]uint, 0, len(allDepts))
	var collectChildren func(uint)
	collectChildren = func(deptId uint) {
		result = append(result, deptId)
		for _, childId := range childrenMap[deptId] {
			collectChildren(childId)
		}
	}
	collectChildren(rootDeptId)
	return result, nil
}

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

	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 {

		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	var dept models.MgtDepartment
	if err := impl.DBService.Select("id", "app_id").Where("id = ?", request.ID).First(&dept).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	allDeptIds, err := getDepartmentIdsRecursive(impl.DBService, dept.AppID, request.ID)
	if err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	if err := impl.DBService.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("dpt_id in ?", allDeptIds).Delete(&models.MgtLinkUserDpt{}).Error; err != nil {
			return err
		}
		if err := tx.Where("dpt_id in ?", allDeptIds).Delete(&models.MgtLinkDptRole{}).Error; err != nil {
			return err
		}
		if err := tx.Where("dpt_id in ?", allDeptIds).Delete(&models.MgtLinkDptPmn{}).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", allDeptIds).Delete(&models.MgtDepartment{}).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

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