/**
 * Projects Hook
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ProjectsService } from '@/lib/api/services/ProjectsService';

export const projectKeys = {
  all: ['projects'] as const,
  lists: () => [...projectKeys.all, 'list'] as const,
  list: (filters: string) => [...projectKeys.lists(), { filters }] as const,
  details: () => [...projectKeys.all, 'detail'] as const,
  detail: (id: string) => [...projectKeys.details(), id] as const,
};

export const useProjectListInfinite = (limit: number = 20) => {
  const query = useQuery({
    queryKey: projectKeys.lists(),
    queryFn: async () => {
      const response = await ProjectsService.listProjects();
      // API returns { data: { items: [...] }, meta: {...} }
      // After camelCase conversion, response.data.items contains the projects
      const data = response.data as any;
      return data?.items || data || [];
    },
  });

  // Return expected structure for page component
  return {
    projects: (query.data as any[]) || [],
    hasNextPage: false,
    fetchNextPage: () => {},
    isFetchingNextPage: query.isFetching,
    isLoading: query.isLoading,
    refetch: query.refetch,
  };
};

export const useDeleteProjectMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (projectId: string) => {
      await ProjectsService.deleteProject(projectId);
      return projectId;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: projectKeys.lists() });
    },
  });
};

export const useProjectWorkspace = (projectId: string) => {
  return useQuery({
    queryKey: projectKeys.detail(projectId),
    queryFn: async () => {
      const response = await ProjectsService.getProject(projectId);
      return response;
    },
    enabled: !!projectId,
    refetchInterval: (query) => {
      const project = (query.state.data as any)?.data?.data ?? (query.state.data as any)?.data;
      return project?.status === 'initializing' ? 2000 : false;
    },
  });
};
