import api from './api'; import { CartItem } from '../store/cartStore'; export interface OrderItem { id: string; orderId: string; productId: string | null; quantity: number; product?: any; } export interface Order { id: string; userId: string; couponId: string | null; totalAmount: number; charityDonation: number; status: string; trackingNumber: string | null; createdAt: string; orderItems: OrderItem[]; } export class OrderService { private static instance: OrderService; private constructor() {} public static getInstance(): OrderService { if (!OrderService.instance) { OrderService.instance = new OrderService(); } return OrderService.instance; } /** * Create a new order on the backend */ public async createOrder(orderData: { petId?: string; couponCode?: string; prescriptionUrl?: string; charityDonation?: number; paymentMethod?: string; isRefill?: boolean; refillIntervalDays?: number; shippingAddress?: string; items: { productId: string; quantity: number }[]; }): Promise { try { const response = await api.post('/orders', orderData); return response.data; } catch (error: any) { const message = error.response?.data?.message || 'خطا در ثبت سفارش'; throw new Error(Array.isArray(message) ? message[0] : message); } } /** * Get all orders for the current user */ public async getUserOrders(): Promise { try { const response = await api.get('/orders'); return response.data.data; } catch (error: any) { const message = error.response?.data?.message || 'خطا در دریافت لیست سفارش‌ها'; throw new Error(Array.isArray(message) ? message[0] : message); } } /** * Get order details by ID */ public async getOrderById(id: string): Promise { try { const response = await api.get(`/orders/${id}`); return response.data; } catch (error: any) { const message = error.response?.data?.message || 'خطا در دریافت جزئیات سفارش'; throw new Error(Array.isArray(message) ? message[0] : message); } } } export const orderService = OrderService.getInstance();