package com.ruoyi.app.omgpay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import static com.ruoyi.app.omgpay.OmgPaymentErrorCode.AUTH_REQUIRED;
import static com.ruoyi.app.omgpay.OmgPaymentErrorCode.ORDER_REQUIRED;
import static com.ruoyi.app.omgpay.OmgPaymentErrorCode.PAYMENT_REFUND_UNAVAILABLE_IN_TEST_ENVIRONMENT;

/**
 * Test-stage refund boundary. OMG publishes no refund endpoint for its test environment,
 * so this service must fail closed before reading payment facts or changing local state.
 */
@Service
public class OmgPaymentRefundService {
    private static final Logger log = LoggerFactory.getLogger(OmgPaymentRefundService.class);

    public Void refund(Long userId, String orderId) {
        if (userId == null) {
            throw business(AUTH_REQUIRED);
        }
        String normalizedOrderId = normalizeOrderId(orderId);
        log.warn("OMG refund blocked environment=TEST, orderId={}, userId={}, reason=GATEWAY_UNAVAILABLE",
                OmgPaymentController.safeLogOrderId(normalizedOrderId), userId);
        throw business(PAYMENT_REFUND_UNAVAILABLE_IN_TEST_ENVIRONMENT);
    }

    private static String normalizeOrderId(String orderId) {
        if (orderId == null || orderId.isBlank()) {
            throw business(ORDER_REQUIRED);
        }
        String normalized = orderId.trim();
        if (normalized.length() > 64) {
            throw business(ORDER_REQUIRED);
        }
        return normalized;
    }

    private static OmgPaymentBusinessException business(OmgPaymentErrorCode code) {
        return new OmgPaymentBusinessException(code);
    }
}
