import { apiClient } from '@/lib/api-client';
import type {
  ProductByIdResponse,
  ProductFilters,
  ProductMutationPayload,
  ProductsResponse
} from './types';

export async function getProducts(filters: ProductFilters): Promise<ProductsResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.categories) searchParams.set('categories', filters.categories);
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.sort) searchParams.set('sort', filters.sort);

  return apiClient<ProductsResponse>(`/products?${searchParams.toString()}`);
}

export async function getProductById(id: number): Promise<ProductByIdResponse> {
  return apiClient<ProductByIdResponse>(`/products/${id}`);
}

export async function createProduct(data: ProductMutationPayload) {
  return apiClient<ProductByIdResponse>('/products', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateProduct(id: number, data: ProductMutationPayload) {
  return apiClient<ProductByIdResponse>(`/products/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteProduct(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/products/${id}`, {
    method: 'DELETE'
  });
}
