package com.ruoyi.app.pay;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.InfoUser;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.PosOrderLinePayment;
import com.ruoyi.system.service.IPosOrderLinePaymentService;
import org.springframework.stereotype.Service;

import java.util.List;

/** Enforces merchant ownership and prevents accepting an unpaid real LINE order. */
@Service
public class LinePayOrderGuard {
    private final IPosOrderLinePaymentService paymentService;

    public LinePayOrderGuard(IPosOrderLinePaymentService paymentService) {
        this.paymentService = paymentService;
    }

    public void requireMerchantOwnership(PosOrder order, InfoUser user) {
        if (order == null || user == null || user.getUserId() == null) {
            throw new ServiceException("No permission to operate this order");
        }
        if ("0".equals(user.getUserType()) || "2".equals(user.getUserType())) {
            throw new ServiceException("No permission to operate this order");
        }
        boolean merchant = "1".equals(user.getUserType()) || "3".equals(user.getUserType());
        boolean owned = merchant
                ? user.getUserId().equals(order.getShId())
                : user.getStoreId() != null && user.getStoreId().equals(order.getMdId());
        if (!owned) {
            throw new ServiceException("No permission to operate this order");
        }
    }

    public void requirePaidBeforeAccept(PosOrder order) {
        if (order == null || !LinePayService.PAY_TYPE_LINE.equals(order.getPayType())
                || Long.valueOf(1L).equals(order.getPayStatus())) {
            return;
        }
        List<PosOrderLinePayment> attempts = paymentService.getByDdId(String.valueOf(order.getDdId()));
        if (attempts != null && !attempts.isEmpty()) {
            throw new ServiceException("LINE Pay order is not paid yet");
        }
    }

    /** Applies ownership rules to the still-supported legacy order-state endpoint. */
    public void requireLegacyOrderActor(PosOrder order, InfoUser user, Long targetState) {
        if (user == null || user.getUserId() == null) {
            throw new ServiceException("No permission to operate this order");
        }
        if ("2".equals(user.getUserType())) {
            boolean riderState = Long.valueOf(3L).equals(targetState)
                    || Long.valueOf(4L).equals(targetState)
                    || Long.valueOf(12L).equals(targetState);
            boolean assignedRider = order != null && order.getQsId() != null
                    && user.getUserId().equals(order.getQsId());
            if (!riderState || !assignedRider) {
                throw new ServiceException("No permission to operate this order");
            }
            return;
        }
        requireMerchantOwnership(order, user);
    }
}
