import api from '@/lib/api';
import type { 
  ApiProduct, 
  ApiProductsResponse, 
  ApiCategory 
} from '@/types/api';

// Product API Service
export const productApi = {
  // Get all products with optional filters
  async getProducts(params?: {
    search?: string;
    category_id?: number;
    page?: number;
    sort_by?: 'created_at' | 'name' | 'base_price' | 'updated_at';
    sort_order?: 'asc' | 'desc';
  }): Promise<ApiProductsResponse> {
    const queryParams = new URLSearchParams();
    
    if (params?.search) queryParams.append('search', params.search);
    if (params?.category_id) queryParams.append('category_id', params.category_id.toString());
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.sort_by) queryParams.append('sort_by', params.sort_by);
    if (params?.sort_order) queryParams.append('sort_order', params.sort_order);
    
    const query = queryParams.toString();
    const endpoint = query ? `/products?${query}` : '/products';
    
    return api.get<ApiProductsResponse>(endpoint);
  },

  // Get single product by slug
  async getProduct(slug: string): Promise<{ data: ApiProduct }> {
    return api.get<{ data: ApiProduct }>(`/products/${slug}`);
  },

  // Get categories
  async getCategories(): Promise<ApiCategory[]> {
    return api.get<ApiCategory[]>('/categories');
  },
};

export default productApi;
