/**
 * Entity History hooks — undo/restore functionality.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiGet, apiPost, apiClient } from './client';

export interface EntityHistoryEntry {
  id: string;
  entity_type: string;
  entity_id: string;
  action: 'create' | 'update' | 'delete';
  snapshot_before: Record<string, any> | null;
  snapshot_after: Record<string, any> | null;
  changes: Record<string, { old: any; new: any }> | null;
  user_id: string | null;
  created_at: string;
}

export interface EntityHistoryList {
  items: EntityHistoryEntry[];
  total: number;
}

export function useEntityHistory(entityType?: string, entityId?: string) {
  return useQuery({
    queryKey: ['entityHistory', entityType, entityId],
    queryFn: () =>
      apiGet<EntityHistoryList>(`/entity-history/${entityType}/${entityId}`),
    enabled: !!entityType && !!entityId,
  });
}

export function useRestoreFromHistory() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (historyId: string) =>
      apiClient.post('/entity-history/restore', { history_id: historyId }).then(r => r.data),
    onSuccess: (_data, _variables, context) => {
      queryClient.invalidateQueries({ queryKey: ['entityHistory'] });
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
      queryClient.invalidateQueries({ queryKey: ['contact'] });
    },
  });
}

export function useUndoLastAction() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ entityType, entityId }: { entityType: string; entityId: string }) =>
      apiPost(`/entity-history/undo/${entityType}/${entityId}`, {}),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['entityHistory'] });
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
      queryClient.invalidateQueries({ queryKey: ['contact'] });
    },
  });
}
