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"
)

func FetchTree(c *gin.Context) {
	var (
		request = types.DptReq{}
		data    = make([]models.MgtDepartment, 0)
	)
	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.Workspace == "" {
		printer.Error("workspace is required: workspace=%s", request.Workspace)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	appModel := models.MgtApplication{Workspace: request.Workspace}
	appId, err := appModel.WorkspaceToId()
	if err != nil {
		printer.Error("workspace not found: workspace=%s", request.Workspace)
		infra.Response.Error(c, errcode.ErrRecordNotFound)
		return
	}

	if err := models.DBService.Model(&models.MgtDepartment{}).
		Where("app_id = ?", appId).
		Select("id", "identity", "name", "app_id", "parent_id").
		Order("parent_id asc").Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	tree := buildDeptTree(data, 0)
	infra.Response.Success(c, types.FetchResp{Data: tree})
}
