// src/middlewares/usage-logger.middleware.js
// 사용량 로깅 미들웨어

const { UsageLog } = require('../models');
const logger = require('../config/logger.config');

/**
 * 사용량 로깅 미들웨어
 * 응답 완료 후 사용량 정보를 데이터베이스에 저장
 */
exports.usageLogger = (req, res, next) => {
  // 응답 완료 후 처리
  res.on('finish', async () => {
    try {
      // 사용량 데이터가 없으면 스킵
      if (!req.usageData) {
        return;
      }

      const usageData = {
        userId: req.user?.id || req.user?.userId,
        apiKeyId: req.apiKey?.id || null,
        providerId: req.usageData.providerId || null,
        providerName: req.usageData.providerName || null,
        modelName: req.usageData.modelName || null,
        promptTokens: req.usageData.promptTokens || 0,
        completionTokens: req.usageData.completionTokens || 0,
        totalTokens: req.usageData.totalTokens || 0,
        costUsd: req.usageData.costUsd || 0,
        responseTimeMs: req.usageData.responseTimeMs || null,
        success: req.usageData.success !== false,
        errorMessage: req.usageData.errorMessage || null,
        requestIp: req.ip || req.connection?.remoteAddress,
        userAgent: req.headers['user-agent'] || null,
      };

      await UsageLog.create(usageData);

      logger.debug('사용량 로그 저장:', {
        userId: usageData.userId,
        tokens: usageData.totalTokens,
        cost: usageData.costUsd,
      });
    } catch (error) {
      logger.error('사용량 로그 저장 실패:', error);
    }
  });

  next();
};
