const express = require("express");
const router = express.Router();
const { Order } = require("../models");

const {
  handleError,
  handleSuccess,
  handleSequelizeError,
  deepEqual,
} = require("../utils");

// GET all orders
router.get("/", async (_, res) => {
  try {
    const orders = await Order.findAll();
    handleSuccess(res, orders);
  } catch (err) {
    handleSequelizeError(err, res);
  }
});

// GET one order by id
router.get("/:id", async (req, res) => {
  try {
    const order = await Order.findByPk(req.params.id);
    if (!order) return handleError("Order not found", 404, res);
    handleSuccess(res, order);
  } catch (err) {
    handleSequelizeError(err, res);
  }
});

// POST create an order
router.post("/", async (req, res) => {
  try {
    const { order_id, user_id, shipping_dock_id, amount, notes } = req.body;
    if (
      order_id === undefined ||
      user_id === undefined ||
      shipping_dock_id === undefined ||
      amount === undefined ||
      notes === undefined
    ) {
      return handleError("All fields are required", 400, res);
    }
    const order = await Order.create(req.body);
    handleSuccess(res, order, 201);
  } catch (err) {
    handleError(err.message, 500, res);
  }
});

// PUT update an order
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const order = await Order.findByPk(id);
    if (!order) return handleError("Order not found", 404, res);

    // Only allow updating amount, notes, and status
    const allowedFields = ["amount", "notes", "status"];
    const changes = {};
    for (const key of allowedFields) {
      if (
        req.body[key] !== undefined &&
        !deepEqual(req.body[key], order[key])
      ) {
        changes[key] = req.body[key];
      }
    }

    // Validate status if present
    if (
      changes.status !== undefined &&
      ![0, 1].includes(Number(changes.status))
    ) {
      return handleError("Status must be 0 or 1", 400, res);
    }

    if (Object.keys(changes).length === 0) {
      return handleError("No updated fields", 400, res); // No changes
    }

    await order.update(changes);
    handleSuccess(res, await Order.findByPk(id));
  } catch (err) {
    handleSequelizeError(err, res);
  }
});

// DELETE an order
router.delete("/:id", async (req, res) => {
  try {
    const deleted = await Order.destroy({
      where: { id: req.params.id },
    });
    if (deleted === 0) return handleError("Order not found", 404, res);
    handleSuccess(res, null, 204); // 204 No Content
  } catch (err) {
    handleSequelizeError(err, res);
  }
});

module.exports = router;
