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

import type { UpdateIssueParams } from '@/client/models/UpdateIssueParams';
import { IssuesService } from '@/client/services/IssuesService';

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

  return useMutation({
    mutationFn: (params: UpdateIssueParams) => {
      if (!workspaceName || number === null) throw new Error('Missing params');
      return IssuesService.issueUpdate({ workspaceName, number, requestBody: params });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['workspace', workspaceName, 'issues'] });
      qc.invalidateQueries({ queryKey: ['workspace', workspaceName, 'issues', number] });
    },
  });
}
