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

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

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

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