package cn.nianxx.thhotel.platform.navigation.repository;

import cn.nianxx.thhotel.platform.navigation.common.enums.PlatformMenuStatus;
import cn.nianxx.thhotel.platform.navigation.domain.PlatformMenuEntity;
import cn.nianxx.thhotel.platform.navigation.mapper.PlatformMenuMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Repository;

/**
 * 基于 MyBatis-Plus 的平台菜单仓储实现。
 */
@Repository
public class MybatisPlatformNavigationRepository implements PlatformNavigationRepository {

    private final PlatformMenuMapper menuMapper;

    public MybatisPlatformNavigationRepository(PlatformMenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    public Optional<PlatformMenuEntity> findMenuByCode(String menuCode) {
        return Optional.ofNullable(menuMapper.selectOne(Wrappers.<PlatformMenuEntity>lambdaQuery()
                .eq(PlatformMenuEntity::getMenuCode, menuCode)
                .last("LIMIT 1")));
    }

    @Override
    public void insertMenu(PlatformMenuEntity menu) {
        menuMapper.insert(menu);
    }

    @Override
    public void updateMenu(PlatformMenuEntity menu) {
        menuMapper.updateById(menu);
    }

    @Override
    public List<PlatformMenuEntity> listVisibleMenus(List<String> permissionCodes) {
        if (permissionCodes == null || permissionCodes.isEmpty()) {
            return menuMapper.selectList(Wrappers.<PlatformMenuEntity>lambdaQuery()
                    .eq(PlatformMenuEntity::getMenuStatus, PlatformMenuStatus.ACTIVE.name())
                    .eq(PlatformMenuEntity::getVisible, true)
                    .isNull(PlatformMenuEntity::getPermissionCode)
                    .orderByAsc(PlatformMenuEntity::getSortOrder)
                    .orderByAsc(PlatformMenuEntity::getMenuCode));
        }
        return menuMapper.selectList(Wrappers.<PlatformMenuEntity>lambdaQuery()
                .eq(PlatformMenuEntity::getMenuStatus, PlatformMenuStatus.ACTIVE.name())
                .eq(PlatformMenuEntity::getVisible, true)
                .and(wrapper -> wrapper.isNull(PlatformMenuEntity::getPermissionCode)
                        .or()
                        .in(!permissionCodes.isEmpty(), PlatformMenuEntity::getPermissionCode, permissionCodes))
                .orderByAsc(PlatformMenuEntity::getSortOrder)
                .orderByAsc(PlatformMenuEntity::getMenuCode));
    }
}
