/**
 * @ai-summary React Query hooks for unified audit log management
 * @ai-context Handles fetching, filtering, and exporting audit logs
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminApi } from '../api/admin.api';
import { AuditLogFilters, UnifiedAuditLogsResponse } from '../types/admin.types';

const AUDIT_LOGS_KEY = 'unifiedAuditLogs';

/**
 * Hook to fetch unified audit logs with filtering and pagination
 */
export function useUnifiedAuditLogs(filters: AuditLogFilters = {}) {
  return useQuery<UnifiedAuditLogsResponse, Error>({
    queryKey: [AUDIT_LOGS_KEY, filters],
    queryFn: () => adminApi.unifiedAuditLogs.list(filters),
    staleTime: 30000, // 30 seconds
  });
}

/**
 * Hook to export audit logs as CSV
 */
export function useExportAuditLogs() {
  return useMutation({
    mutationFn: async (filters: AuditLogFilters) => {
      const blob = await adminApi.unifiedAuditLogs.export(filters);

      // Create download link
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;

      // Generate filename with current date
      const date = new Date().toISOString().split('T')[0];
      link.download = `audit-logs-${date}.csv`;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      return true;
    },
  });
}

/**
 * Hook to invalidate audit logs cache (useful after actions that create logs)
 */
export function useInvalidateAuditLogs() {
  const queryClient = useQueryClient();

  return () => {
    queryClient.invalidateQueries({ queryKey: [AUDIT_LOGS_KEY] });
  };
}
