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

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

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

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

// POST create a shipping dock
router.post("/", async (req, res) => {
  try {
    const { name } = req.body;
    if (!name || !name.trim()) {
      return handleError("Name is required and cannot be empty", 400, res);
    }
    await ShippingDock.create(req.body);
    handleSuccess(res, null, 201);
  } catch (err) {
    handleError(err.message, 500, res);
  }
});

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

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

    // Build changes object dynamically
    const changes = {};
    for (const key in req.body) {
      if (req.body[key] !== undefined && !deepEqual(req.body[key], dock[key])) {
        changes[key] = req.body[key];
      }
    }

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

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

// DELETE a shipping dock
router.delete("/:id", async (req, res) => {
  try {
    const deleted = await ShippingDock.destroy({
      where: { id: req.params.id },
    });
    if (deleted === 0) return handleError("Dock not found", 404, res);
    handleSuccess(res, null);
  } catch (err) {
    handleSequelizeError(err, res);
  }
});

module.exports = router;
