/**
 * @ai-summary React Query hooks for admin user management
 * @ai-context List, create, revoke, and reinstate admins
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { adminApi } from '../api/admin.api';
import { CreateAdminRequest } from '../types/admin.types';
import toast from 'react-hot-toast';

interface ApiError {
  response?: {
    data?: {
      error?: string;
    };
  };
  message?: string;
}

export const useAdmins = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['admins'],
    queryFn: () => adminApi.listAdmins(),
    enabled: isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes cache time
    retry: 1,
    refetchOnWindowFocus: false,
  });
};

export const useCreateAdmin = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateAdminRequest) => adminApi.createAdmin(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admins'] });
      toast.success('Admin added successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to add admin');
    },
  });
};

export const useRevokeAdmin = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (auth0Sub: string) => adminApi.revokeAdmin(auth0Sub),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admins'] });
      toast.success('Admin revoked successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to revoke admin');
    },
  });
};

export const useReinstateAdmin = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (auth0Sub: string) => adminApi.reinstateAdmin(auth0Sub),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admins'] });
      toast.success('Admin reinstated successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to reinstate admin');
    },
  });
};

export const useAuditLogs = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['auditLogs'],
    queryFn: () => adminApi.listAuditLogs(),
    enabled: isAuthenticated && !isLoading,
    staleTime: 2 * 60 * 1000, // 2 minutes - audit logs should be relatively fresh
    gcTime: 5 * 60 * 1000,
    retry: 1,
    refetchOnWindowFocus: false,
  });
};
