import { Router } from "express";
import Customer from "../models/Customer.js";
import { requireAuth } from "../middleware/auth.js";

const router = Router();

router.use(requireAuth);

router.get("/daily", async (req, res) => {
  try {
    const { date } = req.query;
    if (!date) {
      return res.status(400).json({ message: "date query parameter is required (YYYY-MM-DD)." });
    }

    const start = new Date(date);
    const end = new Date(date);
    end.setDate(end.getDate() + 1);

    const rows = await Customer.find({
      userId: req.session.userId
    })
      .populate("ProductCode")
      .populate("order_number")
      .sort({ createdAt: -1 });

    const report = rows.filter((row) => {
      if (!row.order_number?.order_date) return false;
      const dt = new Date(row.order_number.order_date);
      return dt >= start && dt < end;
    });

    return res.json(report);
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }
});

export default router;
