import { nanoid } from "nanoid";
import { Order } from "../models/Order.js";

export async function createOrder(request, response) {
  const order = await Order.create({
    ...request.body,
    customer: request.user._id,
    tracking: { trackingCode: `OMS-${nanoid(9).toUpperCase()}`, events: [{ status: "Pending", note: "Order created" }] }
  });
  request.app.get("io").to(String(request.user._id)).emit("order:created", order);
  response.status(201).json(order);
}

export async function updateOrderStatus(request, response) {
  const { status, note, location } = request.body;
  const order = await Order.findByIdAndUpdate(
    request.params.id,
    { status, $push: { "tracking.events": { status, note, location } } },
    { new: true }
  );
  request.app.get("io").to(String(order.customer)).emit("order:updated", order);
  response.json(order);
}

export async function listOrders(request, response) {
  const query = request.user.role === "customer" ? { customer: request.user._id } : {};
  const orders = await Order.find(query).sort("-createdAt").limit(100);
  response.json(orders);
}
