package com.jeesharp.business.modules.pay.config.log;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.framework.log.api.constant.InterfaceLogResultConstant;
import com.jeesharp.framework.log.api.entity.InterfaceLogEntity;
import com.jeesharp.framework.log.api.mapper.InterfaceLogMapper;
import com.jeesharp.framework.log.api.service.InterfaceLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 将框架 {@link InterfaceLogService} 默认实现（仅打日志）替换为落库 {@code interface_log}。
 * <p>供 {@code ExternalApiClient}、进件客户端等统一持久化接口日志。</p>
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Slf4j
@Service
@Primary
@RequiredArgsConstructor
@ConditionalOnBean(InterfaceLogMapper.class)
public class InterfaceLogPersistServiceImpl implements InterfaceLogService {

    private final InterfaceLogMapper interfaceLogMapper;

    @Override
    public void save(InterfaceLogEntity entity) {
        if (entity == null) {
            return;
        }
        log.info("接口调用日志 - 场景类型: {}, URL: {}, 状态: {}, 耗时: {}ms",
                entity.getScenarioType(), entity.getRequestUrl(), entity.getResponseStatus(), entity.getDuration());
        if (InterfaceLogResultConstant.FAIL.equals(entity.getResponseStatus())
                || InterfaceLogResultConstant.ERROR.equals(entity.getResponseStatus())) {
            log.warn("接口调用失败 - URL: {}, 错误信息: {}", entity.getRequestUrl(), entity.getErrorMessage());
        }
        try {
            if (StrUtil.isBlank(entity.getId())) {
                entity.setId(IdUtil.fastSimpleUUID());
            }
            if (entity.getCreateDate() == null) {
                entity.setCreateDate(new Date());
            }
            interfaceLogMapper.insert(entity);
        } catch (Exception e) {
            log.error("保存接口日志到 interface_log 失败, url={}", entity.getRequestUrl(), e);
        }
    }
}
