package com.zioinfo.esn.service;

import com.zioinfo.esn.domain.UpdateQueueVo;
import com.zioinfo.esn.mapper.UpdateQueueMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UpdateQueueService {
    private final UpdateQueueMapper mapper;

    public List<UpdateQueueVo> list(String tenantCode, Long storeId, String status) {
        return mapper.findAll(tenantCode, storeId, status);
    }

    public UpdateQueueVo get(Long id) { return mapper.findById(id); }

    /** Gateway 폴링: PENDING 큐 N건 반환 후 SENDING으로 전환 */
    @Transactional
    public List<UpdateQueueVo> pollPending(String tenantCode, int limit) {
        List<UpdateQueueVo> items = mapper.findPending(tenantCode, limit);
        for (UpdateQueueVo q : items) {
            mapper.updateStatus(q.getId(), "SENDING", null);
        }
        return items;
    }

    /** Gateway → 태그 전송 완료 */
    @Transactional
    public void markSent(Long id) {
        mapper.updateStatus(id, "SENT", null);
    }

    /** 태그 확인 응답 수신 (device_id 기반) */
    @Transactional
    public void confirm(String deviceId) {
        mapper.confirmByDeviceId(deviceId);
    }

    /** 전송 실패 처리 — max_retry 초과 시 FAILED */
    @Transactional
    public void markFailed(Long id, String errorMessage) {
        UpdateQueueVo q = mapper.findById(id);
        if (q == null) return;
        mapper.incrementRetry(id);
        if (q.getRetryCount() + 1 >= q.getMaxRetry()) {
            mapper.updateStatus(id, "FAILED", errorMessage);
        } else {
            mapper.updateStatus(id, "PENDING", errorMessage);
        }
    }

    @Transactional
    public void cancel(Long id) {
        mapper.updateStatus(id, "CANCELLED", null);
    }
}
