import { keepPreviousData, useQuery } from '@tanstack/react-query';

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

interface PrFilters {
  state?: string | null;
  authorId?: string | null;
  draft?: boolean | null;
  limit?: number;
  offset?: number;
}

export function usePrList(
  workspaceName: string | null,
  repoName: string | null,
  filters: PrFilters = {},
) {
  return useQuery({
    queryKey: ['workspace', workspaceName, 'repos', repoName, 'prs', filters],
    queryFn: () => {
      if (!workspaceName || !repoName) throw new Error('Missing params');
      return PullRequestsService.prList({
        workspaceName,
        repoName,
        state: filters.state,
        authorId: filters.authorId,
        draft: filters.draft,
        limit: filters.limit ?? 50,
        offset: filters.offset ?? 0,
      }).then((r) => r.data);
    },
    enabled: !!workspaceName && !!repoName,
    placeholderData: keepPreviousData,
    staleTime: 1000 * 60 * 2,
  });
}
