/**
 * User Routes
 * Handles user profile and usage information
 */

const express = require('express');
const router = express.Router();
const { query } = require('../database/connection');
const { authenticateJWT } = require('../middleware/auth');

/**
 * GET /v1/user/usage
 * Get API usage statistics for the authenticated user
 */
router.get('/usage', authenticateJWT, async (req, res, next) => {
    try {
        const userId = req.user.id;

        // Get total and successful/failed calls
        const statsResult = await query(
            `SELECT 
         COUNT(*) as total_calls,
         COUNT(*) FILTER (WHERE success = true) as successful_calls,
         COUNT(*) FILTER (WHERE success = false) as failed_calls,
         COALESCE(SUM(credits_used), 0) as credits_used
       FROM api_calls 
       WHERE user_id = $1 
       AND called_at >= DATE_TRUNC('month', CURRENT_DATE)`,
            [userId]
        );

        // Get breakdown by endpoint
        const endpointResult = await query(
            `SELECT endpoint, COUNT(*) as count
       FROM api_calls 
       WHERE user_id = $1 
       AND called_at >= DATE_TRUNC('month', CURRENT_DATE)
       GROUP BY endpoint
       ORDER BY count DESC`,
            [userId]
        );

        const stats = statsResult.rows[0];
        const byEndpoint = {};
        endpointResult.rows.forEach(row => {
            byEndpoint[row.endpoint] = parseInt(row.count);
        });

        res.json({
            success: true,
            data: {
                period: 'month',
                total_calls: parseInt(stats.total_calls) || 0,
                successful_calls: parseInt(stats.successful_calls) || 0,
                failed_calls: parseInt(stats.failed_calls) || 0,
                credits_used: parseInt(stats.credits_used) || 0,
                quota: req.user.monthly_quota,
                remaining: req.user.monthly_quota - req.user.calls_this_month,
                by_endpoint: byEndpoint
            }
        });

    } catch (error) {
        next(error);
    }
});

/**
 * GET /v1/user/profile
 * Get user profile information
 */
router.get('/profile', authenticateJWT, async (req, res, next) => {
    try {
        res.json({
            success: true,
            data: {
                id: req.user.id,
                email: req.user.email,
                company_name: req.user.company_name,
                plan: req.user.plan,
                quota: req.user.monthly_quota,
                used: req.user.calls_this_month
            }
        });
    } catch (error) {
        next(error);
    }
});

/**
 * GET /v1/user/api-keys
 * Get all API keys for the user
 */
router.get('/api-keys', authenticateJWT, async (req, res, next) => {
    try {
        const result = await query(
            `SELECT id, key_prefix, key_hint, name, is_test_key, is_active, last_used_at, total_calls, created_at
       FROM api_keys 
       WHERE user_id = $1
       ORDER BY created_at DESC`,
            [req.user.id]
        );

        res.json({
            success: true,
            data: {
                api_keys: result.rows.map(key => ({
                    id: key.id,
                    name: key.name,
                    key_preview: `${key.key_prefix}****${key.key_hint}`,
                    is_test_key: key.is_test_key,
                    is_active: key.is_active,
                    last_used_at: key.last_used_at,
                    total_calls: key.total_calls,
                    created_at: key.created_at
                }))
            }
        });
    } catch (error) {
        next(error);
    }
});

module.exports = router;
