import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import api from '@/services/api';
import { useCartStore } from '@/store/cart';
import type { Sale } from '@/types';

// DTO que coincide con backend CreateSaleDto
interface CreateSaleDto {
  items: {
    productId: string;
    quantity: number;
    discountPercent?: number;
  }[];
  paymentMethodId: string;
  amountReceived: number;
  customerName?: string;
  customerPhone?: string;
  notes?: string;
}

// Response del backend para summary
interface TodaySummary {
  totalSales: number;
  totalRevenue: number;
  totalTax: number;
  avgTicket: number;
}

export function useCreateSale() {
  const queryClient = useQueryClient();
  const clearCart = useCartStore((state) => state.clear);

  return useMutation({
    mutationFn: async (sale: CreateSaleDto) => {
      // Backend: POST /sales
      const { data } = await api.post<Sale>('/sales', sale);
      return data;
    },
    onSuccess: () => {
      clearCart();
      queryClient.invalidateQueries({ queryKey: ['sales'] });
      queryClient.invalidateQueries({ queryKey: ['daily-summary'] });
      queryClient.invalidateQueries({ queryKey: ['products'] }); // Stock updated
    },
  });
}

export function useTodaySales() {
  return useQuery({
    queryKey: ['sales', 'today'],
    queryFn: async () => {
      // Backend: GET /sales/recent?limit=50
      const { data } = await api.get<Sale[]>('/sales/recent?limit=50');
      return data;
    },
  });
}

export function useDailySummary() {
  return useQuery({
    queryKey: ['daily-summary'],
    queryFn: async () => {
      // Backend: GET /sales/today
      const { data } = await api.get<TodaySummary>('/sales/today');
      return data;
    },
  });
}

export function useCancelSale() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ saleId, reason }: { saleId: string; reason?: string }) => {
      // Backend: POST /sales/:id/cancel
      const { data } = await api.post<Sale>(`/sales/${saleId}/cancel`, { reason });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['sales'] });
      queryClient.invalidateQueries({ queryKey: ['daily-summary'] });
      queryClient.invalidateQueries({ queryKey: ['products'] }); // Stock restored
    },
  });
}
