package cn.novalon.gym.manage.db.repository;

import cn.novalon.gym.manage.sys.core.domain.SysExceptionLog;
import cn.novalon.gym.manage.sys.core.repository.ISysExceptionLogRepository;
import cn.novalon.gym.manage.common.dto.PageRequest;
import cn.novalon.gym.manage.common.dto.PageResponse;
import cn.novalon.gym.manage.db.converter.SysExceptionLogConverter;
import cn.novalon.gym.manage.db.dao.SysExceptionLogDao;
import cn.novalon.gym.manage.db.dao.QueryUtil;
import cn.novalon.gym.manage.db.entity.SysExceptionLogEntity;
import cn.novalon.gym.manage.db.entity.query.SysExceptionLogQueryCriteria;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
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.time.LocalDateTime;
import java.util.List;

/**
 * 异常日志仓储实现类
 * 
 * @author 张翔
 * @date 2026-03-13
 */
@Repository
public class SysExceptionLogRepository implements ISysExceptionLogRepository {

    private final SysExceptionLogDao sysExceptionLogDao;
    private final SysExceptionLogConverter sysExceptionLogConverter;
    private final R2dbcEntityTemplate r2dbcEntityTemplate;

    public SysExceptionLogRepository(SysExceptionLogDao sysExceptionLogDao,
            SysExceptionLogConverter sysExceptionLogConverter, R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.sysExceptionLogDao = sysExceptionLogDao;
        this.sysExceptionLogConverter = sysExceptionLogConverter;
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    @Override
    public Flux<SysExceptionLog> findAllByOrderByCreateTimeDesc() {
        return sysExceptionLogDao.findAllByOrderByCreateTimeDesc()
                .map(sysExceptionLogConverter::toDomain);
    }

    @Override
    public Flux<SysExceptionLog> findByUsernameOrderByCreateTimeDesc(String username) {
        SysExceptionLogQueryCriteria criteria = new SysExceptionLogQueryCriteria();
        criteria.setUsername(username);

        Query dbQuery = QueryUtil.getQuery(criteria);
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        dbQuery = dbQuery.sort(sort);

        return r2dbcEntityTemplate.select(SysExceptionLogEntity.class)
                .matching(dbQuery)
                .all()
                .map(sysExceptionLogConverter::toDomain);
    }

    @Override
    public Flux<SysExceptionLog> findByCreateTimeBetweenOrderByCreateTimeDesc(LocalDateTime startTime,
            LocalDateTime endTime) {
        Criteria criteria = Criteria.where("createTime").between(startTime, endTime);
        Query dbQuery = Query.query(criteria);
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        dbQuery = dbQuery.sort(sort);

        return r2dbcEntityTemplate.select(SysExceptionLogEntity.class)
                .matching(dbQuery)
                .all()
                .map(sysExceptionLogConverter::toDomain);
    }

    @Override
    public Mono<SysExceptionLog> save(SysExceptionLog exceptionLog) {
        SysExceptionLogEntity entity = sysExceptionLogConverter.toEntity(exceptionLog);
        return sysExceptionLogDao.save(entity)
                .map(sysExceptionLogConverter::toDomain);
    }

    @Override
    public Mono<SysExceptionLog> findById(Long id) {
        return sysExceptionLogDao.findById(id)
                .map(sysExceptionLogConverter::toDomain);
    }

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

    @Override
    public Mono<PageResponse<SysExceptionLog>> findExceptionLogsByPage(PageRequest pageRequest) {
        int page = pageRequest.getPage();
        int size = pageRequest.getSize();
        String sort = pageRequest.getSort();
        String order = pageRequest.getOrder();
        String keyword = pageRequest.getKeyword();

        SysExceptionLogQueryCriteria criteria = new SysExceptionLogQueryCriteria();
        
        if (keyword != null && !keyword.isEmpty()) {
            criteria.setKeyword(keyword);
        }

        Query queryObj = QueryUtil.getQuery(criteria);

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

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

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