package com.ruoyi.app.pay;

import com.ruoyi.system.domain.PosOrderLinePayment;
import com.ruoyi.system.service.IPosOrderLinePaymentService;
import com.ruoyi.system.service.IPosOrderLineRefundService;
import org.springframework.stereotype.Service;

import java.util.List;

/** Repairs a cancellation crash gap by creating any missing refund intent for captured payments. */
@Service
public class LinePayCancellationCompensationService {
    private final IPosOrderLinePaymentService paymentService;
    private final IPosOrderLineRefundService refundService;

    public LinePayCancellationCompensationService(IPosOrderLinePaymentService paymentService,
                                                  IPosOrderLineRefundService refundService) {
        this.paymentService = paymentService;
        this.refundService = refundService;
    }

    public void createMissingRefundIntents(List<PosOrderLinePayment> payments) {
        if (payments == null) {
            return;
        }
        payments.stream().filter(payment -> "PAID".equals(payment.getStatus()))
                .forEach(payment -> refundService.createIfAbsent(payment, "CANCEL_SCAN"));
    }

    public void createMissingRefundIntent(String ddId) {
        createMissingRefundIntents(paymentService.getByDdId(ddId));
    }
}
