package org.hzhub.erp.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * API统计记录服务
 * 使用MySQL数据源记录API调用统计信息
 *
 * @author HZHub Team
 */
@Service
@DS("master")  // 使用MySQL数据源记录统计信息
@RequiredArgsConstructor
public class ApiStatsRecorder {

    private static final Logger log = LoggerFactory.getLogger(ApiStatsRecorder.class);
    private final JdbcTemplate jdbcTemplate;

    /**
     * 记录API调用统计
     *
     * @param apiId API ID
     * @param callParams 调用参数（JSON字符串）
     * @param executedSql 实际执行的SQL语句
     * @param responseTime 响应时间（毫秒）
     * @param callStatus 调用状态（SUCCESS/ERROR）
     * @param errorMessage 错误消息（可选）
     * @param errorStack 错误堆栈（可选）
     * @param clientIp 客户端IP
     * @param userId 用户ID
     */
    public void recordApiCall(Long apiId, String callParams, String executedSql,
                              Long responseTime, String callStatus,
                              String errorMessage, String errorStack,
                              String clientIp, String userId) {
        try {
            String sql = "INSERT INTO erp_api_stats " +
                        "(api_id, call_time, call_params, executed_sql, response_time, call_status, " +
                        "error_message, error_stack, client_ip, user_id, create_time) " +
                        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            LocalDateTime now = LocalDateTime.now();
            String callTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            jdbcTemplate.update(sql,
                apiId,
                callTime,
                callParams,
                executedSql,
                responseTime,
                callStatus,
                errorMessage,
                errorStack,
                clientIp,
                userId,
                callTime
            );

            log.info("API调用统计记录成功: apiId={}, status={}, time={}ms",
                    apiId, callStatus, responseTime);

        } catch (Exception e) {
            // 统计记录失败不影响API执行，只记录日志
            log.error("记录API调用统计失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 记录成功的API调用
     */
    public void recordSuccess(Long apiId, String callParams, String executedSql,
                              Long responseTime, String clientIp, String userId) {
        recordApiCall(apiId, callParams, executedSql, responseTime, "SUCCESS",
                     null, null, clientIp, userId);
    }

    /**
     * 记录失败的API调用
     */
    public void recordError(Long apiId, String callParams, String executedSql,
                            Long responseTime, String errorMessage, String errorStack,
                            String clientIp, String userId) {
        recordApiCall(apiId, callParams, executedSql, responseTime, "ERROR",
                     errorMessage, errorStack, clientIp, userId);
    }
}