/**
 * Analytics Service
 * Logs API calls and updates usage counters
 */

const { query } = require('../database/connection');

async function logApiCall({ userId, apiKeyId, endpoint, method, params, status, duration, success, isTestKey, errorMessage = null }) {
    try {
        await query(
            `INSERT INTO api_calls 
       (user_id, api_key_id, endpoint, method, request_params, response_status, response_time_ms, success, error_message, credits_used, is_billable)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
            [userId, apiKeyId, endpoint, method, JSON.stringify(params || {}), status, duration, success, errorMessage, success ? 1 : 0, !isTestKey && success]
        );

        if (success && !isTestKey) {
            await query('UPDATE users SET calls_this_month = calls_this_month + 1 WHERE id = $1', [userId]);
            await query('UPDATE api_keys SET last_used_at = NOW(), total_calls = total_calls + 1 WHERE id = $1', [apiKeyId]);
        }
    } catch (error) {
        console.error('Log error:', error.message);
    }
}

module.exports = { logApiCall };

