'use client';

/**
 * React Query hooks for admin monitor outbox dead events.
 */

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

export interface OutboxDeadEventView {
  id: string;
  eventType: string;
  aggregateType: string;
  retryCount: number;
  lastError: string | null;
  deadAt: string | null;
  failedAt: string | null;
  createdAt: string;
}

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 useDeadOutbox() {
  return useQuery({
    queryKey: keys.outboxDead(),
    queryFn: async () => {
      const data = await fetch('/api/admin/monitor/outbox').then(jsonOrThrow);
      return (data.events as OutboxDeadEventView[]) ?? [];
    },
  });
}

export function useRedriveOutbox(eventId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () =>
      fetch('/api/admin/monitor/outbox/redrive', {
        method: 'POST',
        headers: csrfHeaders(),
        body: JSON.stringify({ id: eventId }),
      }).then(jsonOrThrow),
    onSuccess: () => void qc.invalidateQueries({ queryKey: keys.outboxDead() }),
  });
}
