import { useQuery } from '@tanstack/react-query';
import {
  fetchBurndown,
  fetchPortfolio,
  fetchProjectHealth,
  fetchSprintBurndown,
  fetchSprintCapacity,
  fetchVelocity,
  fetchWorkload,
} from '@/features/projects/services/projectService';

export const burndownQueryKey = (projectId: string) =>
  ['projects', projectId, 'burndown'] as const;

export const sprintBurndownQueryKey = (projectId: string, sprintId: string) =>
  ['projects', projectId, 'sprints', sprintId, 'burndown'] as const;

export const velocityQueryKey = (projectId: string) =>
  ['projects', projectId, 'velocity'] as const;

export const healthQueryKey = (projectId: string) => ['projects', projectId, 'health'] as const;

export const workloadQueryKey = (projectId: string) =>
  ['projects', projectId, 'workload'] as const;

export const portfolioQueryKey = (filters?: Record<string, unknown>) =>
  ['projects', 'portfolio', filters ?? {}] as const;

export function useProjectBurndown(projectId: string | undefined) {
  return useQuery({
    queryKey: burndownQueryKey(projectId ?? ''),
    queryFn: () => fetchBurndown(projectId!),
    enabled: Boolean(projectId),
  });
}

export function useSprintBurndown(projectId: string | undefined, sprintId: string | undefined) {
  return useQuery({
    queryKey: sprintBurndownQueryKey(projectId ?? '', sprintId ?? ''),
    queryFn: () => fetchSprintBurndown(projectId!, sprintId!),
    enabled: Boolean(projectId && sprintId),
  });
}

export function useProjectVelocity(projectId: string | undefined) {
  return useQuery({
    queryKey: velocityQueryKey(projectId ?? ''),
    queryFn: () => fetchVelocity(projectId!),
    enabled: Boolean(projectId),
  });
}

export function useProjectHealth(projectId: string | undefined) {
  return useQuery({
    queryKey: healthQueryKey(projectId ?? ''),
    queryFn: () => fetchProjectHealth(projectId!),
    enabled: Boolean(projectId),
  });
}

export function useProjectWorkload(projectId: string | undefined) {
  return useQuery({
    queryKey: workloadQueryKey(projectId ?? ''),
    queryFn: () => fetchWorkload(projectId!),
    enabled: Boolean(projectId),
  });
}

export function useSprintCapacity(projectId: string | undefined, sprintId: string | undefined) {
  return useQuery({
    queryKey: ['projects', projectId, 'sprints', sprintId, 'capacity'] as const,
    queryFn: () => fetchSprintCapacity(projectId!, sprintId!),
    enabled: Boolean(projectId && sprintId),
  });
}

export function usePortfolio(filters?: Record<string, unknown>) {
  return useQuery({
    queryKey: portfolioQueryKey(filters),
    queryFn: () => fetchPortfolio(filters),
  });
}
