import { fetchData } from '@/lib/data-service'; import { normalizeApiUrl } from './api-utils'; /** * Fetches product data from the API */ export const fetchProductData = async (url: string, authToken: string) => { try { return await fetchData(normalizeApiUrl(url), { headers: { Authorization: `Bearer ${authToken}` }, credentials: "include", }); } catch (error) { console.error("Error fetching product data:", error); throw error; } }; /** * Saves product data to the API */ export const saveProductData = async ( url: string, data: any, authToken: string, method: "POST" | "PUT" = "POST" ) => { try { return await fetchData(normalizeApiUrl(url), { method, headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json", }, credentials: "include", body: JSON.stringify(data), }); } catch (error) { console.error("Error saving product data:", error); throw error; } }; /** * Uploads a product image */ export const saveProductImage = async(url: string, file: File, authToken: string) => { try{ const formData = new FormData(); formData.append("file", file); return await fetchData(normalizeApiUrl(url), { method: "PUT", headers: { Authorization: `Bearer ${authToken}`, }, body: formData, }); } catch (error) { console.error("Error uploading image:", error); throw error; } } /** * Deletes a product */ export const deleteProductData = async (url: string, authToken: string) => { try { return await fetchData(normalizeApiUrl(url), { method: "DELETE", headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json", }, credentials: "include", }); } catch (error) { console.error("Error deleting product data:", error); throw error; } }; /** * Fetches product stock information */ export const fetchStockData = async (url: string, authToken: string) => { try { return await fetchData(normalizeApiUrl(url), { headers: { Authorization: `Bearer ${authToken}` }, credentials: "include", }); } catch (error) { console.error("Error fetching stock data:", error); throw error; } }; /** * Updates product stock information */ export const updateProductStock = async ( productId: string, stockData: { currentStock: number; stockTracking?: boolean; lowStockThreshold?: number; }, authToken: string ) => { try { const url = `/api/stock/${productId}`; return await fetchData(url, { method: "PUT", headers: { Authorization: `Bearer ${authToken}`, "Content-Type": "application/json", }, credentials: "include", body: JSON.stringify(stockData), }); } catch (error) { console.error("Error updating product stock:", error); throw error; } };