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 PermissionsFetch(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").
				Where("id in ?", pmnIds).Find(&perms).Error; err != nil {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
		}
		permMap := make(map[uint]models.MgtPermission)
		for _, p := range perms {
			permMap[p.ID] = p
		}
		for i := range data {
			ids := dptToPmn[data[i].ID]
			data[i].Permissions = make([]models.MgtPermission, 0, len(ids))
			for _, pid := range ids {
				if p, ok := permMap[pid]; ok {
					data[i].Permissions = append(data[i].Permissions, p)
				}
			}
		}
		infra.Response.Success(c, data)
		return
	}

	preloadPerm := func(db *gorm.DB) *gorm.DB {
		return db.Select("id", "identity", "title", "title_en", "sort_key", "parent_id")
	}
	if err := db.Select("id", "identity", "name").Preload("Permissions", preloadPerm).Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}
	infra.Response.Success(c, data)
}
