import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { ChecklistState, ReportUpsert, WorkOrderStatus } from '@siop/shared';
import { api, unwrap } from './client';

/** Hooks R4.2 — mêmes opérations que le web (contrat unique). Les écritures
 *  restent EN LIGNE dans cette release ; la mise en file arrive en R4.3 (D1). */

export function useWorkOrders() {
  return useQuery({
    queryKey: ['work-orders'],
    queryFn: async () => (await unwrap(await api.GET('/work-orders'))).workOrders,
  });
}

export function useWorkOrder(id: string) {
  return useQuery({
    queryKey: ['work-orders', id],
    queryFn: async () =>
      unwrap(await api.GET('/work-orders/{id}', { params: { path: { id } } })),
  });
}

export function useAssets() {
  return useQuery({
    queryKey: ['assets'],
    queryFn: async () => (await unwrap(await api.GET('/assets'))).assets,
  });
}

export function useAsset(id: string) {
  return useQuery({
    queryKey: ['assets', id],
    queryFn: async () => unwrap(await api.GET('/assets/{id}', { params: { path: { id } } })),
  });
}

export function useDocumentsOT(workOrderId: string) {
  return useQuery({
    queryKey: ['documents', workOrderId],
    queryFn: async () =>
      (
        await unwrap(
          await api.GET('/documents', { params: { query: { workOrderId } } }),
        )
      ).documents,
  });
}

export function useReferenceValues() {
  return useQuery({
    queryKey: ['reference-values'],
    staleTime: 3600_000, // référentiels administrables : stables en journée
    queryFn: async () => (await unwrap(await api.GET('/reference-values'))).referenceValues,
  });
}

function useInvalideOT(id: string) {
  const queryClient = useQueryClient();
  return () =>
    Promise.all([
      queryClient.invalidateQueries({ queryKey: ['work-orders', id] }),
      queryClient.invalidateQueries({ queryKey: ['work-orders'] }),
    ]);
}

export function useTransition(id: string) {
  const invalide = useInvalideOT(id);
  return useMutation({
    mutationFn: async (input: { to: WorkOrderStatus; comment?: string }) =>
      unwrap(
        await api.POST('/work-orders/{id}/transition', {
          params: { path: { id } },
          body: input,
        }),
      ),
    onSuccess: invalide,
  });
}

export function useCocheChecklist(otId: string) {
  const invalide = useInvalideOT(otId);
  return useMutation({
    mutationFn: async (input: { itemId: string; state: ChecklistState }) =>
      unwrap(
        await api.PATCH('/work-orders/{id}/checklist/{itemId}', {
          params: { path: { id: otId, itemId: input.itemId } },
          body: { state: input.state },
        }),
      ),
    onSuccess: invalide,
  });
}

/** Suggestion R5 (D1) : l'IA est un service SERVEUR — la suggestion demande le
 *  réseau, la clôture en file R4 fonctionne sans elle. */
export function useSuggestionBilan() {
  return useMutation({
    mutationFn: async (description: string) =>
      unwrap(await api.POST('/assistant/suggest-bilan', { body: { description } })),
  });
}

export function useBilan(otId: string) {
  const invalide = useInvalideOT(otId);
  return useMutation({
    mutationFn: async (body: ReportUpsert) =>
      unwrap(
        await api.PUT('/work-orders/{id}/report', { params: { path: { id: otId } }, body }),
      ),
    onSuccess: invalide,
  });
}
