import { apiClient } from './api/client';
import { Product, Order, License, CreateProductRequest, CreateOrderRequest } from '../types/marketplace';

export const marketplaceService = {
  fetchProducts: async (filters?: Record<string, any>): Promise<Product[]> => {
    const params = new URLSearchParams();
    if (filters) {
      Object.keys(filters).forEach(key => {
        if (filters[key]) params.append(key, filters[key]);
      });
    }
    const response = await apiClient.get<Product[]>(`/marketplace/products?${params.toString()}`);
    return response.data;
  },

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

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

  getDownloadLink: async (productId: string): Promise<string> => {
    const response = await apiClient.get<{ url: string }>(`/marketplace/download/${productId}`);
    return response.data.url;
  },

  getUserLicenses: async (): Promise<License[]> => {
    // Assuming there is an endpoint for this, though not explicitly requested in prompt, it's in the service interface on backend.
    // The backend service has GetUserLicenses, but handler?
    // Looking at handlers/marketplace.go, there isn't a specific endpoint for listing licenses exposed yet?
    // Let's check handlers/marketplace.go content I wrote earlier.
    return []; // Not implemented in handler yet based on my previous output, strictly following prompt which asked for specific endpoints.
  }
};
