package com.ga.common.menu;

import java.util.*;

/**
 * 평면 메뉴 목록 → 트리 구조 변환.
 */
public final class MenuTreeBuilder {

    private MenuTreeBuilder() {}

    public static List<MenuResp> build(List<MenuVO> flat, Map<Long, List<String>> permissionsByMenuId) {
        Map<Long, MenuResp> map = new LinkedHashMap<>();
        // VO → Resp 변환
        for (MenuVO vo : flat) {
            MenuResp r = new MenuResp();
            r.setMenuId(vo.getMenuId());
            r.setParentMenuId(vo.getParentMenuId());
            r.setMenuCode(vo.getMenuCode());
            r.setMenuName(vo.getMenuName());
            r.setMenuType(vo.getMenuType());
            r.setMenuPath(vo.getMenuPath());
            r.setMenuIcon(vo.getMenuIcon());
            r.setComponentPath(vo.getComponentPath());
            r.setMenuLevel(vo.getMenuLevel());
            r.setSortOrder(vo.getSortOrder());
            r.setIsVisible(vo.getIsVisible());
            r.setIsActive(vo.getIsActive());
            if (permissionsByMenuId != null) {
                r.setPermissions(permissionsByMenuId.getOrDefault(vo.getMenuId(), List.of()));
            }
            map.put(vo.getMenuId(), r);
        }

        // 부모 → 자식 연결
        List<MenuResp> roots = new ArrayList<>();
        for (MenuResp r : map.values()) {
            if (r.getParentMenuId() == null) {
                roots.add(r);
            } else {
                MenuResp parent = map.get(r.getParentMenuId());
                if (parent != null) parent.getChildren().add(r);
                else roots.add(r);
            }
        }
        sortRecursive(roots);
        return roots;
    }

    private static void sortRecursive(List<MenuResp> nodes) {
        nodes.sort(Comparator.comparing(MenuResp::getSortOrder, Comparator.nullsLast(Integer::compareTo)));
        for (MenuResp n : nodes) sortRecursive(n.getChildren());
    }
}
