import axiosInstance from "@/utils/axios";

/**
 * Get order by ID
 */
export const getOrderById = async (id) => {
	try {
		const response = await axiosInstance.get(`/orders/${id}`);
		return response.data;
	} catch (error) {
		console.error("Error fetching order:", error);
		return {
			status: false,
			message: error.response?.data?.message || "Failed to fetch order",
		};
	}
};

/**
 * Update order by customer
 * This is the function used by the EditOrderModal component
 */
export const updateOrderByCustomer = async (orderId, updatedData) => {
	try {
		console.log("Sending update request with data:", updatedData);
		const response = await axiosInstance.put(`/orders/${orderId}`, updatedData);
		console.log("Update response:", response.data);
		return response.data;
	} catch (error) {
		console.error("Error updating order:", error);
		return {
			status: false,
			message: error.response?.data?.message || "Failed to update order",
		};
	}
};

/**
 * Get order edit history
 */
export const getOrderEditHistory = async (orderId) => {
	try {
		const response = await axiosInstance.get(`/orders/edit-history/${orderId}`);
		return response.data;
	} catch (error) {
		console.error("Error fetching order edit history:", error);
		return {
			status: false,
			message:
				error.response?.data?.message || "Failed to fetch order edit history",
		};
	}
};

/**
 * Check if order can be edited
 */
export const getOrderEditability = async (orderId) => {
	try {
		const response = await axiosInstance.get(`/orders/editability/${orderId}`);
		return response.data;
	} catch (error) {
		console.error("Error checking order editability:", error);
		return {
			status: false,
			message:
				error.response?.data?.message || "Failed to check order editability",
		};
	}
};

// Export other functions as needed
export const getCustomerOrders = async (email) => {
	try {
		const response = await axiosInstance.get(`/orders/customer/${email}`);
		return response.data;
	} catch (error) {
		console.error("Error fetching customer orders:", error);
		return {
			status: false,
			message:
				error.response?.data?.message || "Failed to fetch customer orders",
		};
	}
};

export const createOrder = async (orderData) => {
	try {
		const response = await axiosInstance.post("/orders/create", orderData);
		return response.data;
	} catch (error) {
		console.error("Error creating order:", error);
		return {
			status: false,
			message: error.response?.data?.message || "Failed to create order",
		};
	}
};

export const applyDiscount = async (code, subtotal) => {
	try {
		const response = await axiosInstance.post("/orders/discount", {
			code,
			subtotal,
		});
		return response.data;
	} catch (error) {
		console.error("Error applying discount:", error);
		return {
			status: false,
			message: error.response?.data?.message || "Failed to apply discount",
		};
	}
};
