'use client';

/**
 * React Query hooks for admin monitor DLQ depth.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getCsrfToken } from '@/lib/csrf';
import { monitorQueryKeys as keys } from './monitorQueryKeys';

export interface DlqQueueView {
  queueKey: string;
  deadCount: number;
  acknowledgedCount: number;
  depth: number;
  lastDeadAt: string | null;
  lastReason: string | null;
}

async function jsonOrThrow(res: Response) {
  const data = (await res.json()) as Record<string, unknown>;
  if (!res.ok || !data.ok) {
    throw new Error((data.error as string) ?? `HTTP ${res.status}`);
  }
  return data;
}

function csrfHeaders(): HeadersInit {
  return {
    'Content-Type': 'application/json',
    'x-csrf-token': getCsrfToken(),
  };
}

export function useDlq() {
  return useQuery({
    queryKey: keys.dlq(),
    queryFn: async () => {
      const data = await fetch('/api/admin/monitor/dlq').then(jsonOrThrow);
      return (data.queues as DlqQueueView[]) ?? [];
    },
  });
}

export function useAcknowledgeDlq(queueKey: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () =>
      fetch(`/api/admin/monitor/dlq/${encodeURIComponent(queueKey)}/acknowledge`, {
        method: 'POST',
        headers: csrfHeaders(),
      }).then(jsonOrThrow),
    onSuccess: () => void qc.invalidateQueries({ queryKey: keys.dlq() }),
  });
}
