package cn.novalon.manage.db.repository;

import cn.novalon.manage.sys.core.domain.SysMenu;
import cn.novalon.manage.sys.core.repository.ISysMenuRepository;
import cn.novalon.manage.sys.core.query.SysMenuQuery;
import cn.novalon.manage.common.dto.PageRequest;
import cn.novalon.manage.common.dto.PageResponse;
import cn.novalon.manage.db.converter.SysMenuConverter;
import cn.novalon.manage.db.dao.SysMenuDao;
import cn.novalon.manage.db.dao.QueryUtil;
import cn.novalon.manage.db.entity.SysMenuEntity;
import cn.novalon.manage.db.entity.query.SysMenuQueryCriteria;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Query;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 菜单仓储实现类
 * 
 * @author 张翔
 * @date 2026-03-13
 */
@Repository
public class SysMenuRepository implements ISysMenuRepository {

    private final SysMenuDao sysMenuDao;
    private final SysMenuConverter sysMenuConverter;
    private final R2dbcEntityTemplate r2dbcEntityTemplate;

    public SysMenuRepository(SysMenuDao sysMenuDao, SysMenuConverter sysMenuConverter,
            R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.sysMenuDao = sysMenuDao;
        this.sysMenuConverter = sysMenuConverter;
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    @Override
    public Flux<SysMenu> findByParentId(Long parentId) {
        return sysMenuDao.findByParentIdAndDeletedAtIsNull(parentId)
                .map(sysMenuConverter::toDomain);
    }

    @Override
    public Flux<SysMenu> findByParentIdOrderBySort(Long parentId, Sort sort) {
        return sysMenuDao.findByParentIdAndDeletedAtIsNull(parentId)
                .map(sysMenuConverter::toDomain);
    }

    @Override
    public Mono<SysMenu> findById(Long id) {
        return sysMenuDao.findByIdAndDeletedAtIsNull(id)
                .map(sysMenuConverter::toDomain);
    }

    @Override
    public Mono<SysMenu> save(SysMenu sysMenu) {
        SysMenuEntity entity = sysMenuConverter.toEntity(sysMenu);
        return sysMenuDao.save(entity)
                .map(sysMenuConverter::toDomain);
    }

    @Override
    public Mono<Void> deleteById(Long id) {
        return sysMenuDao.deleteById(id);
    }

    @Override
    public Flux<SysMenu> findAll() {
        return sysMenuDao.findByDeletedAtIsNull()
                .map(sysMenuConverter::toDomain);
    }

    @Override
    public Flux<SysMenu> findAll(Sort sort) {
        return sysMenuDao.findByDeletedAtIsNull()
                .map(sysMenuConverter::toDomain);
    }

    @Override
    public Mono<Long> count() {
        return sysMenuDao.count();
    }

    @Override
    public Mono<PageResponse<SysMenu>> findByQueryWithPagination(SysMenuQuery query, PageRequest pageRequest) {
        int page = pageRequest.getPage();
        int size = pageRequest.getSize();
        String sort = pageRequest.getSort();
        String order = pageRequest.getOrder();

        Sort sortObj = Sort.unsorted();
        if (sort != null && !sort.isEmpty()) {
            sortObj = Sort.by(Sort.Direction.fromString(order), sort);
        }

        org.springframework.data.domain.PageRequest pageable = org.springframework.data.domain.PageRequest.of(page,
                size, sortObj);

        SysMenuQueryCriteria criteria = new SysMenuQueryCriteria();
        criteria.convert(query);
        Query dbQuery = QueryUtil.getQuery(criteria);

        return r2dbcEntityTemplate.select(SysMenuEntity.class)
                .matching(dbQuery.with(pageable))
                .all()
                .collectList()
                .zipWith(r2dbcEntityTemplate.count(dbQuery, SysMenuEntity.class))
                .map(tuple -> {
                    long total = tuple.getT2();
                    int totalPages = (int) Math.ceil((double) total / size);
                    List<SysMenu> menuList = tuple.getT1().stream()
                            .map(sysMenuConverter::toDomain)
                            .toList();
                    return new PageResponse<>(menuList, totalPages, total, page, size);
                });
    }

    @Override
    public Flux<SysMenu> findByStatus(String status) {
        return sysMenuDao.findByDeletedAtIsNull()
                .map(sysMenuConverter::toDomain);
    }
}