package com.lesingle.modules.leai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.modules.leai.entity.LeaiWebhookEvent;
import com.lesingle.modules.leai.mapper.LeaiWebhookEventMapper;
import com.lesingle.modules.leai.service.ILeaiWebhookEventService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 乐读派 Webhook 事件 Service 实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LeaiWebhookEventServiceImpl extends ServiceImpl<LeaiWebhookEventMapper, LeaiWebhookEvent>
        implements ILeaiWebhookEventService {

    @Override
    public boolean existsByEventId(String eventId) {
        LambdaQueryWrapper<LeaiWebhookEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LeaiWebhookEvent::getEventId, eventId);
        return count(wrapper) > 0;
    }

    @Override
    public void saveEvent(String eventId, String eventType, String remoteWorkId, Object payload) {
        saveEvent(eventId, eventType, remoteWorkId, payload, true, null);
    }

    @Override
    public void saveEvent(String eventId, String eventType, String remoteWorkId, Object payload,
                          boolean success, String errorMsg) {
        LeaiWebhookEvent event = new LeaiWebhookEvent();
        event.setEventId(eventId);
        event.setEventType(eventType);
        event.setRemoteWorkId(remoteWorkId);
        event.setPayload(payload);
        event.setProcessed(success ? 1 : 2);
        event.setErrorMessage(errorMsg);
        event.setRetryCount(0);
        event.setCreateTime(LocalDateTime.now());
        save(event);
    }

    @Override
    public List<LeaiWebhookEvent> findFailedEvents(int maxRetryCount, int limit) {
        LambdaQueryWrapper<LeaiWebhookEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LeaiWebhookEvent::getProcessed, 2); // 处理失败
        wrapper.lt(LeaiWebhookEvent::getRetryCount, maxRetryCount);
        wrapper.orderByAsc(LeaiWebhookEvent::getCreateTime);
        wrapper.last("LIMIT " + limit);
        return list(wrapper);
    }
}
