package department

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 PermissionsFetchTree(c *gin.Context) {
	var (
		request = types.FetchBase{}
		data    = make([]models.MgtDepartment, 0)
		db      = models.DBService.Model(&models.MgtDepartment{})
	)
	if err := c.ShouldBindJSON(&request); 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 {
		db = db.Where("id = ?", request.ID)
	}
	var appId uint
	if request.Workspace != "" {
		appModel := models.MgtApplication{Workspace: request.Workspace}
		var err error
		appId, err = appModel.WorkspaceToId()
		if err != nil {
			printer.Error("workspace not found: workspace=%s", request.Workspace)
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		db = db.Where("app_id = ?", appId)
	}

	if request.Workspace != "" {
		if err := db.Select("id", "identity", "name").Find(&data).Error; err != nil {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		if len(data) == 0 {
			infra.Response.Success(c, data)
			return
		}
		deptIds := make([]uint, 0, len(data))
		for _, d := range data {
			deptIds = append(deptIds, d.ID)
		}
		var links []models.MgtLinkDptPmn
		if err := models.DBService.Where("app_id = ? and dpt_id in ?", appId, deptIds).Find(&links).Error; err != nil {
			infra.Response.Error(c, errcode.ErrDB)
			return
		}
		dptToPmn := make(map[uint][]uint)
		pmnIdSet := make(map[uint]struct{})
		for _, l := range links {
			dptToPmn[l.DptId] = append(dptToPmn[l.DptId], l.PmnId)
			pmnIdSet[l.PmnId] = struct{}{}
		}
		pmnIds := make([]uint, 0, len(pmnIdSet))
		for id := range pmnIdSet {
			pmnIds = append(pmnIds, id)
		}
		var perms []models.MgtPermission
		if len(pmnIds) > 0 {
			if err := models.DBService.Select("id", "identity", "title", "title_en", "sort_key", "parent_id", "menu_path", "code", "component", "is_web_page", "is_new_tab", "web_url").
				Where("id in ?", pmnIds).Order("sort_key").Find(&perms).Error; err != nil {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
		}
		for i := range data {
			ids := dptToPmn[data[i].ID]
			idSet := make(map[uint]struct{})
			for _, id := range ids {
				idSet[id] = struct{}{}
			}
			data[i].Permissions = buildPermTreeFilter(perms, 0, idSet)
		}
		infra.Response.Success(c, data)
		return
	}

	permTreePreload := func(db *gorm.DB) *gorm.DB {
		return db.Select("id", "identity", "title", "title_en", "sort_key", "parent_id", "menu_path", "code", "component", "is_web_page", "is_new_tab", "web_url").
			Where("parent_id = 0").Order("sort_key").
			Preload("Children", func(db *gorm.DB) *gorm.DB {
				return db.Select("id", "identity", "title", "title_en", "sort_key", "parent_id", "menu_path", "code", "component", "is_web_page", "is_new_tab", "web_url").Order("sort_key")
			})
	}

	if err := db.Select("id", "identity", "name").Preload("Permissions", permTreePreload).Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, data)
}

func buildPermTreeFilter(list []models.MgtPermission, parentId uint, idSet map[uint]struct{}) []models.MgtPermission {
	var node []models.MgtPermission
	for _, p := range list {
		if _, ok := idSet[p.ID]; !ok {
			continue
		}
		isRoot := parentId == 0
		parentInSet := false
		if p.ParentID != 0 {
			_, parentInSet = idSet[p.ParentID]
		}
		matches := (p.ParentID == parentId) || (isRoot && p.ParentID != 0 && !parentInSet)
		if !matches {
			continue
		}
		children := buildPermTreeFilter(list, p.ID, idSet)
		if len(children) > 0 {
			p.Children = children
		}
		node = append(node, p)
	}
	return node
}
