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

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

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

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

// POST create a transaction
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 transaction = await Transaction.create(req.body);
    handleSuccess(res, transaction, 201);
  } catch (err) {
    handleError(err.message, 500, res);
  }
});

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

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

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

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

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

module.exports = router;
