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

const router = Router();

router.use(requireAuth);

// GET PRODUCTS (ONLY LOGGED-IN USER)
router.get("/", async (req, res) => {
  try {
    const products = await Product.find({
      userId: req.session.userId
    }).sort({ createdAt: -1 });

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

// CREATE PRODUCT
router.post("/", async (req, res) => {
  try {
    const { productName, productQuantity, unitPrice } = req.body;

    const created = await Product.create({
      productName,
      productQuantity,
      unitPrice,
      userId: req.session.userId
    });

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

// UPDATE PRODUCT
router.put("/:id", async (req, res) => {
  try {
    const { productName, productQuantity, unitPrice } = req.body;

    const updated = await Product.findOneAndUpdate(
      {
        _id: req.params.id,
        userId: req.session.userId
      },
      { productName, productQuantity, unitPrice },
      { new: true, runValidators: true }
    );

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

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

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

    if (linked) {
      return res.status(409).json({ message: "Cannot delete. Product linked to a customer." });
    }

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

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

    return res.json({ message: "Product deleted." });
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }
});

export default router;