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

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

interface IssueFilters {
  state?: string | null;
  priority?: string | null;
  authorId?: string | null;
  assigneeId?: string | null;
  milestoneId?: string | null;
  labelId?: string | null;
  limit?: number;
  offset?: number;
}

export function useIssueList(workspaceName: string | null, filters: IssueFilters = {}) {
  return useQuery({
    queryKey: ['workspace', workspaceName, 'issues', filters],
    queryFn: () => {
      if (!workspaceName) throw new Error('No workspace name');
      return IssuesService.issueList({
        workspaceName,
        state: filters.state,
        priority: filters.priority,
        authorId: filters.authorId,
        assigneeId: filters.assigneeId,
        milestoneId: filters.milestoneId,
        labelId: filters.labelId,
        limit: filters.limit ?? 50,
        offset: filters.offset ?? 0,
      }).then((r) => r.data);
    },
    enabled: !!workspaceName,
    placeholderData: keepPreviousData,
    staleTime: 1000 * 60 * 2,
  });
}
