import { Product } from '../types';
import { apiClient } from './api/client';

export const marketplaceService = {
  listProducts: async (
    params?: {
      status?: string;
      seller_id?: string;
      search?: string;
      product_type?: string;
      min_price?: number;
      max_price?: number;
    },
    pagination?: { page: number; limit: number },
  ) => {
    const queryParams: Record<string, any> = {
      ...params,
      page: pagination?.page || 1,
      limit: pagination?.limit || 12,
    };

    // Rename search to q for backend
    if (params?.search) {
      queryParams.q = params.search;
      delete queryParams.search;
    }
    // Rename product_type to type for backend
    if (params?.product_type) {
      queryParams.type = params.product_type;
      delete queryParams.product_type;
    }

    const response = await apiClient.get<Product[]>('/marketplace/products', {
      params: queryParams,
    });

    // Backend returns just the array for now? Or wrapped?
    // Handler says: response.Success(c, products) which wraps in { success: true, data: [...] }
    // apiClient unwraps response.data.
    // However, backend ListProducts returns just Slice of products.
    // It does NOT return total count yet in the standard response?
    // The handler uses response.Success which usually wraps in "data".
    // But pagination metadata (total, pages) is missing from the backend response structure in the current simplistic implementation.
    // For MVP, if backend doesn't return count, we might have to just return the array and fake total or update backend to return metadata.
    // The previous implementation returned { products, total, page, limit, total_pages }.
    // Let's assume for MVP we return what we have. APIClient unwraps "data".

    // STARTUP FIX: Backend currently just returns []Product in data.
    // We need to match the return type expected by MarketplaceHome: { products: [], total: number ... }
    const items = response.data || [];

    return {
      products: items,
      total: items.length, // Approximate for MVP since backend doesn't return count yet
      page: pagination?.page || 1,
      limit: pagination?.limit || 12,
      total_pages: 1, // Approximate
    };
  },

  // Alias for listProducts to satisfy MarketplaceHome
  fetchProducts: async (filters: any, pagination: any) => {
    return marketplaceService.listProducts(filters, pagination);
  },

  createProduct: async (productData: Partial<Product>) => {
    const response = await apiClient.post<Product>(
      '/marketplace/products',
      productData,
    );
    return response.data;
  },

  createOrder: async (items: { product_id: string }[]) => {
    const response = await apiClient.post<any>('/marketplace/orders', {
      items,
    });
    return response.data;
  },

  // Alias/Wrapper for purchase to satisfy MarketplaceHome
  purchaseProduct: async (productId: string) => {
    return marketplaceService.createOrder([{ product_id: productId }]);
  },

  listOrders: async () => {
    const response = await apiClient.get<any[]>('/marketplace/orders');
    return response.data;
  },
};
