const express = require("express");
const multer = require("multer");
const fs = require("fs");
const { authenticateToken } = require("../middleware/authMiddleware");
const { 
    getAds, addEventAd, updateEventAd, deleteEventAd, getVideoId, updateVideoWebhook} = require("../controllers/adController");
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
    const event_id = req.body.event_id || ''; // Get event ID if available
    
    let uploadPath = `./uploads/`;
    uploadPath += `users/ads/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 events
router.get("/get-event-ads", authenticateToken, getAds); // New route for fetching events

// POST route for creating an event post
router.post('/add-event-ad', authenticateToken, upload.fields([
  { name: 'media', maxCount: 1 },
]), addEventAd);

// Route to update an event by its ID
router.put("/update-event-ad/:id", authenticateToken, upload.fields([
  { name: 'media', maxCount: 1 },
]), updateEventAd);

// Route to delete an existing script by its ID
router.delete("/delete-event-ad/:id", authenticateToken, deleteEventAd);

// Route to get event by URL slug
router.get('/get-video-id/', getVideoId);

// Route to get event by URL slug
router.post('/update-video-webhook', updateVideoWebhook);

module.exports = router;
