/**
 * Publish Events Query Hooks
 *
 * React Query hooks for fetching publish event data.
 */

import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';

interface PublishEvent {
  id: string;
  projectId: string;
  userId: string;
  title: string;
  description: string;
  from_environment: 'dev' | 'stage';
  to_environment: 'stage' | 'production';
  status: 'queued' | 'running' | 'success' | 'failed';
  pages_copied: number;
  audios_copied: number;
  started_at: string | null;
  finished_at: string | null;
  error_message: string | null;
  createdAt: string;
  user?: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
  };
}

interface PublishEventListResponse {
  rows: PublishEvent[];
  count: number;
}

/**
 * Fetch list of publish events for a project
 */
export function usePublishEventsQuery(projectId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.publishEvents.list(projectId || ''),
    queryFn: async (): Promise<PublishEvent[]> => {
      const response = await axios.get<PublishEventListResponse>(
        `publish_events?projectId=${projectId}&limit=50`,
      );
      return response.data.rows;
    },
    enabled: !!projectId,
    staleTime: 1 * 60 * 1000, // Publish events can change quickly
  });
}

export default usePublishEventsQuery;
