import { requireAdmin } from '~/server/utils/auth';
import { getAuditLogs } from '~/server/utils/audit-logger';
import type { AuditLogFilters } from '~/server/utils/audit-logger';

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

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

    // Get query parameters
    const query = getQuery(event);
    
    const filters: AuditLogFilters = {
      startDate: query.startDate as string,
      endDate: query.endDate as string,
      userId: query.userId as string,
      userEmail: query.userEmail as string,
      action: query.action as string,
      resourceType: query.resourceType as string,
      status: query.status as 'success' | 'failure',
      limit: query.limit ? parseInt(query.limit as string) : 50,
      offset: query.offset ? parseInt(query.offset as string) : 0
    };

    // Get audit logs
    const result = await getAuditLogs(filters);

    console.log('[ADMIN] Returning audit logs:', {
      count: result.list.length,
      total: result.totalCount,
      filters
    });

    return {
      success: true,
      data: result.list,
      pagination: {
        total: result.totalCount,
        limit: filters.limit || 50,
        offset: filters.offset || 0,
        hasMore: (filters.offset || 0) + result.list.length < result.totalCount
      }
    };

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

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