package cn.novalon.manage.sys.core.service.impl;

import cn.novalon.manage.sys.core.domain.SysLoginLog;
import cn.novalon.manage.sys.core.repository.ISysLoginLogRepository;
import cn.novalon.manage.sys.core.service.ISysLoginLogService;
import cn.novalon.manage.common.dto.PageRequest;
import cn.novalon.manage.common.dto.PageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * 登录日志服务实现类
 * 
 * @author 张翔
 * @date 2026-03-14
 */
@Service
public class SysLoginLogService implements ISysLoginLogService {

    private static final Logger logger = LoggerFactory.getLogger(SysLoginLogService.class);
    private final ISysLoginLogRepository repository;

    public SysLoginLogService(ISysLoginLogRepository repository) {
        this.repository = repository;
    }

    @Override
    public Flux<SysLoginLog> findAll() {
        return repository.findAllByOrderByLoginTimeDesc();
    }

    @Override
    public Flux<SysLoginLog> findByUsername(String username) {
        return repository.findByUsernameOrderByLoginTimeDesc(username);
    }

    @Override
    public Flux<SysLoginLog> findByLoginTimeBetween(LocalDateTime startTime, LocalDateTime endTime) {
        return repository.findByLoginTimeBetweenOrderByLoginTimeDesc(startTime, endTime);
    }

    @Override
    public Mono<SysLoginLog> save(SysLoginLog loginLog) {
        return repository.save(loginLog);
    }

    @Override
    public Mono<SysLoginLog> findById(Long id) {
        return repository.findById(id);
    }

    @Override
    public Mono<PageResponse<SysLoginLog>> findLoginLogsByPage(PageRequest pageRequest) {
        logger.info("分页查询登录日志: page={}, size={}", pageRequest.getPage(), pageRequest.getSize());
        return repository.findLoginLogsByPage(pageRequest);
    }

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

    @Override
    public Mono<Long> countToday() {
        return repository.countToday();
    }

    @Override
    public Flux<SysLoginLog> findRecent(int limit) {
        logger.info("获取最近{}条登录日志", limit);
        return repository.findAllByOrderByLoginTimeDesc()
                .take(limit);
    }
}