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

import type { UpdatePrParams } from '@/client/models/UpdatePrParams';
import { PullRequestsService } from '@/client/services/PullRequestsService';

export function useUpdatePr(
  workspaceName: string | null,
  repoName: string | null,
  number: number | null,
) {
  const qc = useQueryClient();

  return useMutation({
    mutationFn: (params: UpdatePrParams) => {
      if (!workspaceName || !repoName || number === null) throw new Error('Missing params');
      return PullRequestsService.prUpdate({ workspaceName, repoName, number, requestBody: params });
    },
    onSuccess: () => {
      qc.invalidateQueries({
        queryKey: ['workspace', workspaceName, 'repos', repoName, 'prs'],
      });
      qc.invalidateQueries({
        queryKey: ['workspace', workspaceName, 'repos', repoName, 'prs', number],
      });
    },
  });
}
