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

const router = Router();

router.use(requireAuth);

function toOrderDateKey(value) {
  // Accept YYYY-MM-DD (from <input type="date">) or an ISO string/date.
  // Normalize to calendar day: YYYY-MM-DD.
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return null;
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

// GET ORDERS (USER ONLY)
router.get("/", async (req, res) => {
  const orders = await Order.find({
    userId: req.session.userId
  }).sort({ order_date: -1 });

  return res.json(orders);
});

// CREATE ORDER
router.post("/", async (req, res) => {
  try {
    const { order_date, customer_name } = req.body;
    const order_date_key = toOrderDateKey(order_date);

    if (!order_date_key) {
      return res.status(400).json({ message: "Invalid order_date" });
    }

    const created = await Order.create({
      order_date,
      order_date_key,
      customer_name,
      userId: req.session.userId
    });

    return res.status(201).json(created);
  } catch (err) {
    return res.status(400).json({ message: err.message });
  }
});

// UPDATE ORDER
router.put("/:id", async (req, res) => {
  try {
    const { order_date, customer_name } = req.body;
    const order_date_key = toOrderDateKey(order_date);

    if (!order_date_key) {
      return res.status(400).json({ message: "Invalid order_date" });
    }

    const updated = await Order.findOneAndUpdate(
      {
        _id: req.params.id,
        userId: req.session.userId
      },
      { order_date, order_date_key, customer_name },
      { new: true, runValidators: true }
    );

    if (!updated) return res.status(404).json({ message: "Order not found." });

    return res.json(updated);
  } catch (err) {
    return res.status(400).json({ message: err.message });
  }
});

// DELETE ORDER
router.delete("/:id", async (req, res) => {
  const linked = await Customer.exists({
    order_number: req.params.id,
    userId: req.session.userId
  });

  if (linked) {
    return res.status(409).json({ message: "Order is linked to a customer." });
  }

  const deleted = await Order.findOneAndDelete({
    _id: req.params.id,
    userId: req.session.userId
  });

  if (!deleted) return res.status(404).json({ message: "Order not found." });

  return res.json({ message: "Order deleted." });
});

export default router;
