import { useQuery } from '@tanstack/react-query';
import {
  PedidoErpConsultaResponseSchema,
  PedidoListResponseSchema,
  PedidoDetailSchema,
  type PedidoErpConsultaQuery,
  type PedidoErpConsultaResponse,
  type PedidoListQuery,
  type PedidoListResponse,
  type PedidoDetail,
  type PedidoSummary,
} from '@sar/api-interface';
import { apiFetch } from '../api-client';

export function useOrderList(params: Partial<PedidoListQuery> = {}) {
  const search = new URLSearchParams();
  if (params.idCliente) search.set('idCliente', String(params.idCliente));
  if (params.situa) search.set('situa', String(params.situa));
  if (params.numPedSar) search.set('numPedSar', params.numPedSar);
  if (params.from) search.set('from', params.from);
  if (params.to) search.set('to', params.to);
  if (params.page) search.set('page', String(params.page));
  if (params.limit) search.set('limit', String(params.limit));

  const qs = search.toString();
  return useQuery<PedidoListResponse>({
    queryKey: ['orders', params],
    queryFn: async () => {
      const res = await apiFetch(`/orders${qs ? `?${qs}` : ''}`);
      return PedidoListResponseSchema.parse(res);
    },
  });
}

export function useOrderDetail(id: string | undefined) {
  return useQuery<PedidoDetail>({
    queryKey: ['orders', id],
    enabled: !!id,
    queryFn: async () => {
      // Pedidos ERP têm id 'erp-{idPedido}' — endpoint separado sem ParseUUIDPipe
      const path = id?.startsWith('erp-')
        ? `/orders/erp/${id.replace('erp-', '')}`
        : `/orders/${id}`;
      const res = await apiFetch(path);
      return PedidoDetailSchema.parse(res);
    },
  });
}

export function useClientOrders(idCliente: number | undefined) {
  return useQuery<PedidoSummary[]>({
    queryKey: ['clients', idCliente, 'orders'],
    enabled: idCliente != null,
    queryFn: async () => {
      const res = await apiFetch(`/orders?idCliente=${idCliente}&limit=10`);
      const data = PedidoListResponseSchema.parse(res);
      return data.data;
    },
  });
}

export function useOrderErpConsulta(params: Partial<PedidoErpConsultaQuery> = {}, enabled = true) {
  const search = new URLSearchParams();
  if (params.search) search.set('search', params.search);
  if (params.from) search.set('from', params.from);
  if (params.to) search.set('to', params.to);
  if (params.page) search.set('page', String(params.page));
  if (params.limit) search.set('limit', String(params.limit));

  const qs = search.toString();
  return useQuery<PedidoErpConsultaResponse>({
    queryKey: ['orders-erp-consulta', params],
    enabled,
    queryFn: async () => {
      const res = await apiFetch(`/orders/erp-consulta${qs ? `?${qs}` : ''}`);
      return PedidoErpConsultaResponseSchema.parse(res);
    },
  });
}
