// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.

package org

import (
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
)

type TreeNode struct {
	models.Org
	Children []*TreeNode `json:"children"`
}

func tree(x *vigo.X) ([]*TreeNode, error) {
	var orgs []models.Org
	if err := cfg.DB().Order("level, created_at").Find(&orgs).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	// 构建树结构
	nodeMap := make(map[string]*TreeNode)
	var roots []*TreeNode

	for i := range orgs {
		node := &TreeNode{Org: orgs[i], Children: []*TreeNode{}}
		nodeMap[orgs[i].ID] = node
	}

	for _, node := range nodeMap {
		if node.ParentID != nil && nodeMap[*node.ParentID] != nil {
			parent := nodeMap[*node.ParentID]
			parent.Children = append(parent.Children, node)
		} else {
			roots = append(roots, node)
		}
	}

	return roots, nil
}
