/**
 * Tour Pages Query Hooks
 *
 * React Query hooks for fetching and caching tour page data.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';
import type { TourPage } from '../../types/entities';

interface PagesListResponse {
  rows: TourPage[];
  count: number;
}

/**
 * Fetch tour pages for a project
 */
export function usePagesQuery(
  projectId: string | undefined,
  environment = 'dev',
) {
  return useQuery({
    queryKey: queryKeys.tourPages.list(projectId || '', environment),
    queryFn: async (): Promise<TourPage[]> => {
      const response = await axios.get<PagesListResponse>(
        `tour_pages?projectId=${projectId}&environment=${environment}&limit=500`,
      );
      return response.data.rows;
    },
    enabled: !!projectId,
    staleTime: 2 * 60 * 1000, // 2 minutes (pages change more frequently)
  });
}

/**
 * Fetch single tour page by ID
 */
export function usePageQuery(pageId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.tourPages.detail(pageId || ''),
    queryFn: async (): Promise<TourPage> => {
      const response = await axios.get<TourPage>(`tour_pages/${pageId}`);
      return response.data;
    },
    enabled: !!pageId,
    staleTime: 2 * 60 * 1000,
  });
}

/**
 * Update tour page mutation
 */
export function useUpdatePageMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      data,
    }: {
      id: string;
      data: Partial<TourPage>;
    }): Promise<TourPage> => {
      const response = await axios.put<TourPage>(`tour_pages/${id}`, {
        id,
        data,
      });
      return response.data;
    },
    onSuccess: (data, variables) => {
      // Update the single page cache
      queryClient.setQueryData(queryKeys.tourPages.detail(variables.id), data);
      // Invalidate list queries
      queryClient.invalidateQueries({ queryKey: queryKeys.tourPages.all });
    },
  });
}

/**
 * Create tour page mutation
 */
export function useCreatePageMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: Partial<TourPage>): Promise<TourPage> => {
      const response = await axios.post<TourPage>('tour_pages', { data });
      return response.data;
    },
    onSuccess: () => {
      // Invalidate all page queries to refetch
      queryClient.invalidateQueries({ queryKey: queryKeys.tourPages.all });
    },
  });
}

/**
 * Delete tour page mutation
 */
export function useDeletePageMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (pageId: string): Promise<void> => {
      await axios.delete(`tour_pages/${pageId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tourPages.all });
    },
  });
}

export default usePagesQuery;
