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

import { interchangeDocumentsService } from '@/services/interchange-documents.service';
import type {
  GenerateInterchangeDocumentPayload,
  InterchangeDocumentFilter,
} from '@/types/interchangeDocument';

export const interchangeDocumentKeys = {
  all: ['interchange-documents'] as const,
  list: (filter?: InterchangeDocumentFilter) =>
    ['interchange-documents', 'list', filter ?? {}] as const,
  detail: (id?: string) => ['interchange-documents', 'detail', id ?? ''] as const,
};

export function useInterchangeDocuments(filter?: InterchangeDocumentFilter, enabled = true) {
  return useQuery({
    queryKey: interchangeDocumentKeys.list(filter),
    queryFn: () => interchangeDocumentsService.list(filter).then((r) => r.data),
    enabled,
  });
}

export function useInterchangeDocument(id?: string) {
  return useQuery({
    queryKey: interchangeDocumentKeys.detail(id),
    queryFn: () => interchangeDocumentsService.getById(id as string).then((r) => r.data),
    enabled: Boolean(id),
  });
}

function useInterchangeInvalidation() {
  const qc = useQueryClient();
  return () => {
    qc.invalidateQueries({ queryKey: interchangeDocumentKeys.all });
    qc.invalidateQueries({ queryKey: ['warehouse-inventory', 'export-djibouti-arrival-queue'] });
  };
}

export function useGenerateInterchangeDocument() {
  const onSuccess = useInterchangeInvalidation();
  return useMutation({
    mutationFn: (payload: GenerateInterchangeDocumentPayload) =>
      interchangeDocumentsService.generateFromSchedule(payload),
    onSuccess,
  });
}

export function useAcknowledgeInterchangeDocument() {
  const onSuccess = useInterchangeInvalidation();
  return useMutation({
    mutationFn: (args: { id: string; acknowledgedBy: string; remarks?: string }) =>
      interchangeDocumentsService.acknowledge(args.id, {
        acknowledgedBy: args.acknowledgedBy,
        remarks: args.remarks,
      }),
    onSuccess,
  });
}

export function useDisputeInterchangeDocument() {
  const onSuccess = useInterchangeInvalidation();
  return useMutation({
    mutationFn: (args: { id: string; remarks: string }) =>
      interchangeDocumentsService.dispute(args.id, { remarks: args.remarks }),
    onSuccess,
  });
}

