package com.kamco.cd.kamcoback.postgres.core;

import com.kamco.cd.kamcoback.menu.dto.MenuDto;
import com.kamco.cd.kamcoback.menu.dto.MyMenuDto;
import com.kamco.cd.kamcoback.postgres.entity.MenuEntity;
import com.kamco.cd.kamcoback.postgres.repository.menu.MenuRepository;
import java.util.Comparator;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class MenuCoreService {

  private final MenuRepository menuRepository;

  public List<MenuDto.Basic> getFindAll() {
    return menuRepository.getFindAll().stream().map(MenuEntity::toDto).toList();
  }

  /**
   * 권한별 메뉴 목록
   *
   * @param role
   * @return
   */
  public List<MyMenuDto.Basic> getFindByRole(String role) {
    List<MenuEntity> entities = menuRepository.getFindByRole(role);

    return entities.stream()
        .map(
            parent -> {
              MyMenuDto.Basic p =
                  new MyMenuDto.Basic(
                      parent.getMenuUid(),
                      parent.getMenuNm(),
                      parent.getMenuUrl(),
                      parent.getMenuOrder());

              parent.getChildren().stream()
                  .filter(
                      c ->
                          Boolean.TRUE.equals(c.getIsUse()) && Boolean.FALSE.equals(c.getDeleted()))
                  .sorted(
                      Comparator.comparing(
                          MenuEntity::getMenuOrder, Comparator.nullsLast(Long::compareTo)))
                  .map(
                      c ->
                          new MyMenuDto.Basic(
                              c.getMenuUid(), c.getMenuNm(), c.getMenuUrl(), c.getMenuOrder()))
                  .forEach(childDto -> p.getChildren().add(childDto));

              return p;
            })
        .sorted(
            Comparator.comparing(MyMenuDto.Basic::getOrder, Comparator.nullsLast(Long::compareTo)))
        .toList();
  }

  /**
   * 사용자 role 기준으로 접근 가능한 메뉴 URL 목록 조회
   *
   * @param role
   * @return
   */
  public List<String> findAllowedMenuUrlsByRole(String role) {
    return menuRepository.findAllowedMenuUrlsByRole(role).stream()
        .map(MenuEntity::getMenuUrl)
        .filter(url -> url != null && !url.isBlank())
        .distinct()
        .toList();
  }
}
