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

const router = Router();

router.use(requireAuth);

// GET CUSTOMERS (USER ONLY)
router.get("/", async (req, res) => {
  const customers = await Customer.find({
    userId: req.session.userId
  })
    .populate("ProductCode")
    .populate("order_number")
    .sort({ createdAt: -1 });

  return res.json(customers);
});

// CREATE CUSTOMER
router.post("/", async (req, res) => {
  try {
    const {
      cust_fname,
      cust_lname,
      location,
      telephone,
      ProductCode,
      order_number,
      quantity
    } = req.body;

    const product = await Product.findById(ProductCode);
    const order = await Order.findById(order_number);

    if (!product || !order) {
      return res.status(400).json({ message: "Invalid product or order selected." });
    }

    const qty = Number(quantity);
    if (!qty || qty < 1) {
      return res.status(400).json({ message: "Quantity must be at least 1." });
    }

    if (qty > product.productQuantity) {
      return res.status(400).json({ message: "Insufficient stock" });
    }

    product.productQuantity -= qty;
    await product.save();

    const total_price = qty * product.unitPrice;

    const created = await Customer.create({
      cust_fname,
      cust_lname,
      location,
      telephone,
      ProductCode,
      order_number,
      quantity: qty,
      total_price,
      userId: req.session.userId
    });

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

// UPDATE CUSTOMER
router.put("/:id", async (req, res) => {
  try {
    const {
      cust_fname,
      cust_lname,
      location,
      telephone,
      ProductCode,
      order_number,
      quantity
    } = req.body;

    const existing = await Customer.findOne({
      _id: req.params.id,
      userId: req.session.userId
    });

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

    const product = await Product.findById(ProductCode);
    const order = await Order.findById(order_number);

    if (!product || !order) {
      return res.status(400).json({ message: "Invalid product or order selected." });
    }

    const qty = Number(quantity);
    if (!qty || qty < 1) {
      return res.status(400).json({ message: "Quantity must be at least 1." });
    }

    const total_price = qty * product.unitPrice;

    const updated = await Customer.findOneAndUpdate(
      {
        _id: req.params.id,
        userId: req.session.userId
      },
      {
        cust_fname,
        cust_lname,
        location,
        telephone,
        ProductCode,
        order_number,
        quantity: qty,
        total_price
      },
      { new: true, runValidators: true }
    )
      .populate("ProductCode")
      .populate("order_number");

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

// DELETE CUSTOMER
router.delete("/:id", async (req, res) => {
  const existing = await Customer.findOne({
    _id: req.params.id,
    userId: req.session.userId
  });

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

  const product = await Product.findById(existing.ProductCode);

  if (product) {
    product.productQuantity += Number(existing.quantity || 0);
    await product.save();
  }

  await Customer.findOneAndDelete({
    _id: req.params.id,
    userId: req.session.userId
  });

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

export default router;