/**
 * Project Query Hooks
 *
 * React Query hooks for fetching and caching project data.
 */

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

interface ProjectListParams {
  limit?: number;
  offset?: number;
}

interface ProjectListResponse {
  rows: Project[];
  count: number;
}

/**
 * Fetch list of projects
 */
export function useProjectsQuery(params?: ProjectListParams) {
  const query = params
    ? `?limit=${params.limit || 100}&offset=${params.offset || 0}`
    : '';

  return useQuery({
    queryKey: queryKeys.projects.list(params),
    queryFn: async (): Promise<Project[]> => {
      const response = await axios.get<ProjectListResponse>(`projects${query}`);
      return response.data.rows;
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Fetch single project by ID
 */
export function useProjectQuery(projectId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.projects.detail(projectId || ''),
    queryFn: async (): Promise<Project> => {
      const response = await axios.get<Project>(`projects/${projectId}`);
      return response.data;
    },
    enabled: !!projectId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Update project mutation
 */
export function useUpdateProjectMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      data,
    }: {
      id: string;
      data: Partial<Project>;
    }): Promise<Project> => {
      const response = await axios.put<Project>(`projects/${id}`, {
        id,
        data,
      });
      return response.data;
    },
    onSuccess: (data, variables) => {
      // Update the cache with the new data
      queryClient.setQueryData(queryKeys.projects.detail(variables.id), data);
      // Invalidate list queries to refetch
      queryClient.invalidateQueries({ queryKey: queryKeys.projects.all });
    },
  });
}

export default useProjectQuery;
