text: import express from "express";
  import expressAsyncHandler from "express-async-handler";
  import { Types } from "mongoose";
  import { isAuth } from "../middlewares/isAuth";
  import { isAdmin } from "../middlewares/isAdmin";
  import Order from "../models/OrderModel";
  import Product from "../models/ProdcutModel";
  import User from "../models/UserModel";
  
  const orderRouter = express.Router();
  
  orderRouter.get(
    "/",
    isAuth,
    isAdmin,
    expressAsyncHandler(async (req, res) => {
      const orders = await Order.find({}).populate("user");
      res.send(orders);
    })
  );
  
  orderRouter.get(
    "/mine",
    isAuth,
    expressAsyncHandler(async (req, res) => {
      // console.log(req.user)
      const user = req.user._id;
      if (Types.ObjectId.isValid(user)) {
        const orders = await Order.find({ user });
        // console.log(orders)
        if (orders) res.status(200).send(orders);
      } else res.status(404).send({ message: "Not found" });
    })
  );
  orderRouter.get(
    "/:id",
    isAuth,
    expressAsyncHandler(async (req, res, next) => {
      const orderID = req.params.id;
      if (Types.ObjectId.isValid(orderID)) {
        const order = await Order.findById(req.params.id);
        // console.log(order);
        if (order) res.send(order);
        else res.status(404).send({ message: "Order Not Found" });
      } else next();
    })
  );
  
  orderRouter.post(
    "/",
    isAuth,
    expressAsyncHandler(async (req, res) => {
      // console.log(req.body)
      const {
        shipping,
        payment,
        itemsPrice,
        taxPrice,
        shippingPrice,
        totalPrice,
        orderItems,
      } = req.body;
  
      const order = new Order({
        orderItems,
        user: req.user._id,
        shipping,
        payment,
        itemsPrice,
        taxPrice,
        shippingPrice,
        totalPrice,
      });
      const createOrder = await order.save();
  
      if (createOrder)
        res
          .status(201)
          .send({ message: "new order Created", order: createOrder });
      else res.status(401).send({ error: "Can't created , try again" });
    })
  );
  orderRouter.delete(
    "/:id",
    isAuth,
    isAdmin,
    expressAsyncHandler(async (req, res) => {
      const order = await Order.findById(req.params.id);
      if (order) {
        const deletedOrder = await order.remove();
        res.send({ message: "Order Deleted", product: deletedOrder });
      } else {
        res.status(404).send({ message: "Order Not Found" });
      }
    })
  );
  orderRouter.put(
    "/:id/pay",
    isAuth,
    expressAsyncHandler(async (req, res) => {
      const order = await Order.findById(req.params.id);
      if (order) {
        order.isPaid = true;
        order.paidAt = Date.now();
        order.payment.paymentResult = {
          payerID: req.body.payerID,
          orderID: req.body.orderID,
          paymentID: req.body.paymentID,
        };
        const updatedOrder = await order.save();
        // console.log(updatedOrder)
        res.send({ message: "Order paid", order: updatedOrder });
      } else {
        res.status(404).send({ message: "Order not found" });
      }
    })
  );
  orderRouter.put(
    "/:id/deliver",
    isAuth,
    isAdmin,
    expressAsyncHandler(async (req, res) => {
      const order = await Order.findById(req.params.id);
      if (!order) res.status(404).send({ message: "Order not found" });
      else {
        order.isDeliverd = true;
        order.deliverdAt = Date.now();
  
        const updatedOrder = await order.save();
        res.send({ message: "Order deliverd successfully", order: updatedOrder });
      }
    })
  );
  orderRouter.get(
    "/summary",
    isAuth,
    isAdmin,
    expressAsyncHandler(async (req, res) => {
      const orders = await Order.aggregate([
        {
          $group: {
            _id: null,
            numOrders: { $sum: 1 },
            totalSales: { $sum: "$totalPrice" },
          },
        },
      ]);
      const users = await User.aggregate([
        {
          $group: {
            _id: null,
            numUsers: { $sum: 1 },
          },
        },
      ]);
      const dailyOrders = await Order.aggregate([
        {
          $group: {
            _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
            orders: { $sum: 1 },
            sales: { $sum: "$totalPrice" },
          },
        },
      ]);
      const productCategories = await Product.aggregate([
        {
          $group: {
            _id: "$category",
            count: { $sum: 1 },
          },
        },
      ]);
      res.send({
        users,
        orders: orders.length === 0 ? [{ numOrders: 0, totalSales: 0 }] : orders,
        dailyOrders,
        productCategories,
      });
    })
  );
  export default orderRouter;
  