import { Router } from "express";
import multer from "multer";
import path from "node:path";
import {
  approveTransaction,
  createTransaction,
  listTransactions,
  markPaid,
  updateTransaction
} from "../controllers/transaction.controller.js";
import { authenticate, requireRole, requireExpirationCheck } from "../middleware/auth.middleware.js";
import { roles } from "../utils/constants.js";

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, "uploads/transactions/"),
  filename: (req, file, cb) => cb(null, `TX-${Date.now()}${path.extname(file.originalname)}`)
});
const upload = multer({ storage });

const router = Router();

router.get("/", authenticate, requireExpirationCheck, listTransactions);
router.post("/", authenticate, requireExpirationCheck, requireRole(roles.TELLER, roles.OWNER), upload.single("attachment"), createTransaction);
router.patch("/:id/pay", authenticate, requireExpirationCheck, requireRole(roles.PAYMENT), markPaid);
router.patch("/:id/decision", authenticate, requireExpirationCheck, requireRole(roles.EXECUTIVE), approveTransaction);
router.put("/:id", authenticate, requireExpirationCheck, requireRole(roles.TELLER), updateTransaction);

export default router;
