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

import cn.novalon.gym.manage.common.dto.PageRequest;
import cn.novalon.gym.manage.common.dto.PageResponse;
import cn.novalon.gym.manage.sys.core.domain.OperationLog;
import cn.novalon.gym.manage.sys.core.query.OperationLogQuery;
import cn.novalon.gym.manage.sys.core.repository.IOperationLogRepository;
import cn.novalon.gym.manage.db.converter.OperationLogConverter;
import cn.novalon.gym.manage.db.dao.OperationLogDao;
import cn.novalon.gym.manage.db.dao.QueryUtil;
import cn.novalon.gym.manage.db.entity.OperationLogEntity;
import cn.novalon.gym.manage.db.entity.query.OperationLogQueryCriteria;
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.time.LocalDateTime;
import java.util.List;

/**
 * 操作日志仓储实现类
 * 
 * @author 张翔
 * @date 2026-03-13
 */
@Repository
public class OperationLogRepository implements IOperationLogRepository {

    private final OperationLogDao operationLogDao;
    private final OperationLogConverter operationLogConverter;
    private final R2dbcEntityTemplate r2dbcEntityTemplate;

    public OperationLogRepository(OperationLogDao operationLogDao, OperationLogConverter operationLogConverter,
            R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.operationLogDao = operationLogDao;
        this.operationLogConverter = operationLogConverter;
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    @Override
    public Mono<OperationLog> findById(Long id) {
        return operationLogDao.findById(id)
                .map(operationLogConverter::toDomain);
    }

    @Override
    public Mono<OperationLog> save(OperationLog operationLog) {
        OperationLogEntity entity = operationLogConverter.toEntity(operationLog);
        if (entity.isNew()) {
            return r2dbcEntityTemplate.insert(OperationLogEntity.class)
                    .using(entity)
                    .doOnNext(e -> e.markNotNew())
                    .map(operationLogConverter::toDomain);
        }
        return operationLogDao.save(entity)
                .map(operationLogConverter::toDomain);
    }

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

    @Override
    public Flux<OperationLog> findAll() {
        return operationLogDao.findByDeletedAtIsNull()
                .map(operationLogConverter::toDomain);
    }

    @Override
    public Flux<OperationLog> findByUsername(String username) {
        return operationLogDao.findByUsernameAndDeletedAtIsNull(username)
                .map(operationLogConverter::toDomain);
    }

    @Override
    public Mono<PageResponse<OperationLog>> findByQueryWithPagination(OperationLogQuery 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);

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

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

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

    @Override
    public Mono<Long> countByCreatedAtAfter(LocalDateTime dateTime) {
        return operationLogDao.countByCreatedAtAfterAndDeletedAtIsNull(dateTime);
    }
}