/**
 * @ai-summary Hook for streaming audit logs with polling
 * @ai-context Polls audit logs every 5 seconds with pagination support
 */

import { useState, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { adminApi, AuditLogsResponse } from '../api/admin.api';
import { AdminAuditLog } from '../types/admin.types';

/**
 * Options for audit log stream
 */
interface AuditLogStreamOptions {
  resourceType?: 'admin' | 'catalog' | 'station';
  limit?: number;
  pollIntervalMs?: number;
}

/**
 * Pagination state
 */
interface PaginationState {
  offset: number;
  limit: number;
  total: number;
}

/**
 * Return type for audit log stream hook
 */
interface UseAuditLogStreamReturn {
  logs: AdminAuditLog[];
  loading: boolean;
  error: any;
  pagination: PaginationState;
  hasMore: boolean;
  nextPage: () => void;
  prevPage: () => void;
  refetch: () => void;
  lastUpdated: Date;
}

/**
 * Custom hook for streaming audit logs with polling
 * Uses polling until SSE backend is available
 *
 * @example
 * ```typescript
 * const { logs, loading, nextPage, prevPage } = useAuditLogStream({
 *   resourceType: 'catalog',
 *   limit: 50,
 *   pollIntervalMs: 5000
 * });
 * ```
 */
export function useAuditLogStream(
  options: AuditLogStreamOptions = {}
): UseAuditLogStreamReturn {
  const { resourceType, limit = 50, pollIntervalMs = 5000 } = options;

  const { isAuthenticated, isLoading: authLoading } = useAuth0();

  const [offset, setOffset] = useState(0);
  const [lastUpdated, setLastUpdated] = useState(new Date());

  // Query for fetching audit logs
  const {
    data: auditLogResponse,
    isLoading,
    error,
    refetch,
  } = useQuery<AuditLogsResponse>({
    queryKey: ['auditLogs', resourceType, offset, limit],
    queryFn: async () => {
      const logs = await adminApi.listAuditLogs();
      setLastUpdated(new Date());
      return logs;
    },
    enabled: isAuthenticated && !authLoading,
    staleTime: pollIntervalMs,
    gcTime: 10 * 60 * 1000, // 10 minutes
    retry: 1,
    refetchInterval: pollIntervalMs,
    refetchOnWindowFocus: false,
  });

  // Filter logs by resource type if specified
  const rawLogs = auditLogResponse?.logs;
  const logs = Array.isArray(rawLogs) ? rawLogs : [];
  const totalFromApi =
    typeof auditLogResponse?.total === 'number'
      ? auditLogResponse.total
      : logs.length;

  const filteredLogs = resourceType
    ? logs.filter((log) => log.resourceType === resourceType)
    : logs;

  // Apply pagination
  const paginatedLogs = filteredLogs.slice(offset, offset + limit);

  // Calculate pagination state
  const paginationTotal = resourceType ? filteredLogs.length : totalFromApi;
  const pagination: PaginationState = {
    offset,
    limit,
    total: paginationTotal,
  };

  const hasMore = offset + limit < paginationTotal;

  /**
   * Navigate to next page
   */
  const nextPage = useCallback(() => {
    if (hasMore) {
      setOffset((prev) => prev + limit);
    }
  }, [hasMore, limit]);

  /**
   * Navigate to previous page
   */
  const prevPage = useCallback(() => {
    setOffset((prev) => Math.max(0, prev - limit));
  }, [limit]);

  /**
   * Manual refetch wrapper
   */
  const manualRefetch = useCallback(() => {
    refetch();
  }, [refetch]);

  return {
    logs: paginatedLogs,
    loading: isLoading,
    error,
    pagination,
    hasMore,
    nextPage,
    prevPage,
    refetch: manualRefetch,
    lastUpdated,
  };
}
