import type { Job } from 'types';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useClient } from './useClient';

type JobFilters = {
  lane?: string;
  type?: string;
  status?: string;
};

function buildQuery(filters?: JobFilters) {
  const params = new URLSearchParams();
  if (filters?.lane) params.set('lane', filters.lane);
  if (filters?.type) params.set('type', filters.type);
  if (filters?.status) params.set('status', filters.status);
  const qs = params.toString();
  return qs ? `/queue/jobs?${qs}` : '/queue/jobs';
}

export const useJobs = (filters?: JobFilters) => {
  const client = useClient();
  const queryClient = useQueryClient();

  const { data: jobs = [], refetch } = useQuery<Job[]>({
    queryKey: ['jobs', filters],
    queryFn: () => client.get<Job[]>(buildQuery(filters)),
    refetchInterval: (query) => {
      const data = query.state.data;
      if (!data) return 3000;
      const hasActive = data.some((j) => j.status === 'queued' || j.status === 'running');
      return hasActive ? 3000 : false;
    },
  });

  const invalidate = () => queryClient.invalidateQueries({ queryKey: ['jobs'] });

  const createMutation = useMutation({
    mutationFn: (params: { lane: string; type: string; meta?: Record<string, unknown>; notify?: boolean }) =>
      client.post<Job>('/queue/jobs', params),
    onSuccess: invalidate,
  });

  const cancelMutation = useMutation({
    mutationFn: (id: string) => client.delete<Job>(`/queue/jobs/${id}`),
    onSuccess: invalidate,
  });

  return {
    jobs,
    refetch,
    createJob: createMutation.mutateAsync,
    cancelJob: cancelMutation.mutateAsync,
  };
};

export const useJob = (id: string | null) => {
  const client = useClient();

  const { data: job } = useQuery<Job>({
    queryKey: ['job', id],
    queryFn: () => client.get<Job>(`/queue/jobs/${id}`),
    enabled: !!id,
    refetchInterval: (query) => {
      const data = query.state.data;
      if (!data) return 2000;
      const isActive = data.status === 'queued' || data.status === 'running';
      return isActive ? 2000 : false;
    },
  });

  return { job: job ?? null };
};
