const express = require("express");
const multer = require("multer");
const fs = require("fs");

const { authenticateToken } = require("../middleware/authMiddleware");
const { addUser, getAllUsers, updateUser, getUserDetails, updateUserDetails } = require("../controllers/userController");
const router = express.Router();



// Set up multer storage configuration
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // cb(null, "uploads/"); // Define the folder to store uploaded files
    
    const userId = req.body.user_id || '1'; // Get user ID from request body or token
    
    let uploadPath = `./uploads/`;
    uploadPath += `users/user_id_${userId}`;

    // Create directory if it doesn't exist
    fs.mkdirSync(uploadPath, { recursive: true });

    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + "-" + file.originalname); // Save the file with a unique name
  },
});

const upload = multer({ storage: storage });


// Route to fetch all users
router.get("/get-all-users", authenticateToken, getAllUsers); // New route for fetching users

// Route to add a new user
router.post("/add-user", authenticateToken, addUser); 

// Route to update a user by its ID
router.put("/update-user/:id", authenticateToken, updateUser);


// Route to get user details by user ID
router.get("/get-user-details", authenticateToken, getUserDetails);  // New route to get user details by ID

// Route to update an event by its ID
router.put("/update-user-details", authenticateToken, upload.fields([
  { name: 'company_logo', maxCount: 1 },
  { name: 'favicon_image', maxCount: 1 },
  { name: 'thumbnail_image', maxCount: 1 }
]), updateUserDetails);

// Public routes - No need of authentication ----------



module.exports = router;
