import { api } from './client';
import type { ApiResponse, Part, PartFilters, PaginatedResult } from '../../types';

export interface CreatePartRequest {
  sku: string;
  name: string;
  description?: string;
  categoryId?: string;
  brand?: string;
  manufacturer?: string;
  compatibleEngines?: string[];
  cost?: number;
  price: number;
  currentStock?: number;
  minStock?: number;
  maxStock?: number;
  reorderPoint?: number;
  locationId?: string;
  unit?: string;
  barcode?: string;
  preferredSupplierId?: string;
}

export interface UpdatePartRequest {
  sku?: string;
  name?: string;
  description?: string;
  categoryId?: string | null;
  brand?: string;
  manufacturer?: string;
  compatibleEngines?: string[];
  cost?: number;
  price?: number;
  currentStock?: number;
  minStock?: number;
  maxStock?: number | null;
  reorderPoint?: number | null;
  locationId?: string | null;
  unit?: string;
  barcode?: string;
  preferredSupplierId?: string | null;
  isActive?: boolean;
}

export const partsApi = {
  list: (filters?: PartFilters) => {
    const params = new URLSearchParams();
    if (filters?.categoryId) params.append('categoryId', filters.categoryId);
    if (filters?.isActive !== undefined) params.append('isActive', String(filters.isActive));
    if (filters?.lowStock) params.append('lowStock', 'true');
    if (filters?.search) params.append('search', filters.search);
    if (filters?.page) params.append('page', String(filters.page));
    if (filters?.pageSize) params.append('limit', String(filters.pageSize));

    return api.get<ApiResponse<PaginatedResult<Part>>>(`/parts?${params.toString()}`);
  },

  getById: (id: string) =>
    api.get<ApiResponse<Part>>(`/parts/${id}`),

  create: (data: CreatePartRequest) =>
    api.post<ApiResponse<Part>>('/parts', data),

  update: (id: string, data: UpdatePartRequest) =>
    api.patch<ApiResponse<Part>>(`/parts/${id}`, data),

  delete: (id: string) =>
    api.delete<ApiResponse<null>>(`/parts/${id}`),

  // Search by SKU or barcode
  search: (query: string) =>
    api.get<ApiResponse<Part[]>>(`/parts/search?q=${encodeURIComponent(query)}`),

  // Get low stock items
  getLowStock: () =>
    api.get<ApiResponse<Part[]>>('/parts/low-stock'),
};
