import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams } from 'react-router-dom';

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

export function useStarRepo() {
  const { workspaceName = '', repoName = '' } = useParams();
  const qc = useQueryClient();

  return useMutation({
    mutationFn: () => ReposService.repoStar({ workspaceName, repoName }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['repo', workspaceName, repoName, 'stars'] });
      qc.invalidateQueries({ queryKey: ['repo', workspaceName, repoName, 'stats'] });
    },
  });
}

export function useUnstarRepo() {
  const { workspaceName = '', repoName = '' } = useParams();
  const qc = useQueryClient();

  return useMutation({
    mutationFn: () => ReposService.repoUnstar({ workspaceName, repoName }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['repo', workspaceName, repoName, 'stars'] });
      qc.invalidateQueries({ queryKey: ['repo', workspaceName, repoName, 'stats'] });
    },
  });
}
