import { requireAdmin } from '~/server/utils/auth';
import { getAuditStats } from '~/server/utils/audit-logger';

export default defineEventHandler(async (event) => {
  console.log('[ADMIN] Audit stats request');

  try {
    // Require admin authentication
    await requireAdmin(event);

    // Get query parameters
    const query = getQuery(event);
    const days = query.days ? parseInt(query.days as string) : 30;

    // Get audit statistics
    const stats = await getAuditStats(days);

    console.log('[ADMIN] Returning audit stats:', {
      totalEvents: stats.totalEvents,
      days
    });

    return {
      success: true,
      data: stats
    };

  } catch (error: any) {
    console.error('[ADMIN] Failed to get audit stats:', error);
    
    if (error.statusCode === 403) {
      return {
        success: false,
        error: 'Insufficient permissions. Admin access required.'
      };
    }

    return {
      success: false,
      error: 'Failed to retrieve audit statistics'
    };
  }
});
