package com.jeesharp.business.modules.finance.payorder.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.finance.payorder.entity.PayOrder;
import com.jeesharp.business.modules.finance.payorder.service.PayOrderService;
import com.jeesharp.business.modules.pay.api.PayOrderTenantLookup;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 从财务支付单解析租户 ID，供支付中心按租户选择渠道配置。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Service
@AllArgsConstructor
public class PayOrderTenantLookupImpl implements PayOrderTenantLookup {

    private final PayOrderService payOrderService;

    @Override
    public String findTenantIdByOutTradeNo(String outTradeNo) {
        if (StrUtil.isBlank(outTradeNo)) {
            return null;
        }
        PayOrder order = payOrderService.getByOutTradeNo(outTradeNo.trim());
        return order == null ? null : normalizeTenant(order.getTenantId());
    }

    @Override
    public String findTenantIdByPayOrderId(String payOrderId) {
        if (StrUtil.isBlank(payOrderId)) {
            return null;
        }
        PayOrder order = payOrderService.get(payOrderId.trim());
        return order == null ? null : normalizeTenant(order.getTenantId());
    }

    private static String normalizeTenant(String tenantId) {
        if (tenantId == null) {
            return null;
        }
        String t = tenantId.trim();
        return t.isEmpty() ? null : t;
    }
}
