package logic

import (
	"context"
	"fmt"
	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMenuListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuListLogic {
	return &GetMenuListLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *GetMenuListLogic) GetMenuList(in *system.IdReq) (*system.MenuListResp, error) {
	var menus []sysModel.SundynixMenu
	if err := l.svcCtx.DB.Order("sort ASC").Find(&menus).Error; err != nil {
		l.Errorf("[GetMenuList] ❌ 查询菜单失败: %v", err)
		return nil, fmt.Errorf("查询菜单列表失败")
	}
	l.Infof("[GetMenuList] 查询到菜单数量: %d", len(menus))
	tree := buildMenuTree(menus, "0")
	return &system.MenuListResp{Menus: tree}, nil
}

func buildMenuTree(menus []sysModel.SundynixMenu, parentID string) []*system.MenuInfo {
	var result []*system.MenuInfo
	for _, m := range menus {
		if m.ParentID == parentID {
			info := &system.MenuInfo{
				Id: m.ID, ParentId: m.ParentID, Category: int32(m.Category), Name: m.Name,
				Title: m.Title, Code: m.Code, Path: m.Path, Permission: m.Permission,
				Locale: m.Locale, Icon: m.Icon, Sort: int32(m.Sort),
				Children: buildMenuTree(menus, m.ID),
			}
			result = append(result, info)
		}
	}
	return result
}
