import api from './api';

// Типы данных
export interface OrderItem {
  id: number;
  order_id: number;
  product_id: number;
  variant_id?: number;
  quantity: number;
  price: number;
  product: {
    id: number;
    name: string;
    image?: string;
  };
  variant_name?: string;
}

export interface Order {
  id: number;
  user_id: number;
  status: string;
  total_amount: number;
  shipping_address: string;
  payment_method: string;
  created_at: string;
  updated_at?: string;
  items: OrderItem[];
}

export interface OrderCreate {
  shipping_address_id: number;
  payment_method: string;
  items?: {
    product_id: number;
    variant_id?: number;
    quantity: number;
  }[];
}

export interface OrderUpdate {
  status?: string;
  shipping_address_id?: number;
  payment_method?: string;
}

// Сервис для работы с заказами
export const orderService = {
  // Получить список заказов пользователя
  getUserOrders: async (): Promise<Order[]> => {
    const response = await api.get('/orders');
    return response.data.orders;
  },

  // Получить заказ по ID
  getOrderById: async (id: number): Promise<Order> => {
    const response = await api.get(`/orders/${id}`);
    return response.data;
  },

  // Создать новый заказ
  createOrder: async (order: OrderCreate): Promise<Order> => {
    const response = await api.post('/orders', order);
    return response.data;
  },

  // Обновить заказ
  updateOrder: async (id: number, order: OrderUpdate): Promise<Order> => {
    const response = await api.put(`/orders/${id}`, order);
    return response.data;
  },

  // Отменить заказ
  cancelOrder: async (id: number): Promise<Order> => {
    const response = await api.post(`/orders/${id}/cancel`);
    return response.data;
  }
}; 