'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { PlentyOrder, OrderStatus } from '@/types/integrations';

/** Query key factory */
export const ordersKeys = {
  all: ['orders'] as const,
  list: (filters?: { status?: OrderStatus; limit?: number }) =>
    [...ordersKeys.all, 'list', filters] as const,
  detail: (id: string) => [...ordersKeys.all, 'detail', id] as const,
};

interface FetchOrdersParams {
  status?: OrderStatus;
  limit?: number;
}

/**
 * Fetch orders from PlentyONE
 */
async function fetchOrders(params?: FetchOrdersParams): Promise<PlentyOrder[]> {
  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.status) queryParams.status = params.status;
  if (params?.limit) queryParams.limit = params.limit;

  const response = await api.get<{ orders: PlentyOrder[] } | PlentyOrder[]>(
    '/integrations/plentyone/orders',
    { params: queryParams },
  );
  return Array.isArray(response) ? response : response.orders;
}

/**
 * Fetch a single order by ID
 */
async function fetchOrderById(id: string): Promise<PlentyOrder | null> {
  return api.get<PlentyOrder>(`/integrations/plentyone/orders/${id}`);
}

/**
 * Hook to fetch PlentyONE orders
 */
export function useOrders(params?: FetchOrdersParams) {
  return useQuery({
    queryKey: ordersKeys.list(params),
    queryFn: () => fetchOrders(params),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to fetch a single order
 */
export function useOrder(id: string) {
  return useQuery({
    queryKey: ordersKeys.detail(id),
    queryFn: () => fetchOrderById(id),
    staleTime: 30 * 1000,
    enabled: !!id,
  });
}

/**
 * Get order counts by status
 */
export function useOrderCounts() {
  return useQuery({
    queryKey: [...ordersKeys.all, 'counts'],
    queryFn: async () => {
      const orders = await fetchOrders();
      return {
        new: orders.filter((o) => o.status === 'new').length,
        processing: orders.filter((o) => o.status === 'processing').length,
        shipped: orders.filter((o) => o.status === 'shipped').length,
        delivered: orders.filter((o) => o.status === 'delivered').length,
        cancelled: orders.filter((o) => o.status === 'cancelled').length,
        returned: orders.filter((o) => o.status === 'returned').length,
        total: orders.length,
      };
    },
    staleTime: 30 * 1000,
  });
}
