import { useQuery } from '@tanstack/react-query';
import { useParams } from 'react-router-dom';

import { WorkspacesService } from '@/client/services/WorkspacesService';

export function useCurrentWorkspace() {
  const { workspaceName } = useParams<{ workspaceName: string }>();

  const query = useQuery({
    queryKey: ['workspace', workspaceName],
    queryFn: () => {
      if (!workspaceName) throw new Error('No workspace name');
      return WorkspacesService.workspaceGet({ workspaceName }).then((r) => r.data);
    },
    enabled: !!workspaceName,
    staleTime: 1000 * 60 * 2,
  });

  return { ...query, workspaceName };
}
