const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const { authenticateToken } = require('../middleware/auth');
const {
    createCut,
    getAllCuts,
    getCutById,
    getCutsByUser,
    getCutsByInterests,
    getTrendingCuts,
    updateCut,
    deleteCut,
    toggleLike,
    addComment,
    shareCut
} = require('../controllers/cutsController');

// Configure multer for video uploads
const storage = multer.memoryStorage();

const fileFilter = (req, file, cb) => {
    console.log(`🎬 [UPLOAD DEBUG] File received: ${file.originalname} (${file.mimetype})`);
    
    // Allow video files
    const allowedTypes = [
        'video/mp4',
        'video/avi',
        'video/mov',
        'video/wmv',
        'video/flv',
        'video/webm',
        'video/quicktime',
        'video/x-msvideo',
        'video/x-ms-wmv',
        'video/x-flv',
        'application/octet-stream' // Sometimes videos are sent with this MIME type
    ];
    
    // Check MIME type
    if (allowedTypes.includes(file.mimetype)) {
        console.log(`✅ [UPLOAD DEBUG] Video file accepted: ${file.originalname}`);
        return cb(null, true);
    }
    
    // Check file extension as fallback
    const allowedExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v'];
    const fileExtension = path.extname(file.originalname).toLowerCase();
    
    if (allowedExtensions.includes(fileExtension)) {
        console.log(`✅ [UPLOAD DEBUG] Video file accepted by extension: ${file.originalname}`);
        return cb(null, true);
    }
    
    console.log(`❌ [UPLOAD DEBUG] File rejected: ${file.originalname} (${file.mimetype})`);
    cb(new Error('Invalid file type. Only video files are allowed.'), false);
};

const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 500 * 1024 * 1024, // 500MB limit
        files: 1 // Only one video per cut
    }
});

// Middleware to handle multer errors
const handleMulterError = (error, req, res, next) => {
    if (error instanceof multer.MulterError) {
        console.error(`❌ [MULTER ERROR] ${error.code}: ${error.message}`);
        
        if (error.code === 'LIMIT_FILE_SIZE') {
            return res.status(400).json({
                success: false,
                message: 'File too large. Maximum size is 500MB.'
            });
        }
        
        if (error.code === 'LIMIT_FILE_COUNT') {
            return res.status(400).json({
                success: false,
                message: 'Too many files. Only one video per cut is allowed.'
            });
        }
        
        return res.status(400).json({
            success: false,
            message: `Upload error: ${error.message}`
        });
    }
    
    if (error.message === 'Invalid file type. Only video files are allowed.') {
        return res.status(400).json({
            success: false,
            message: error.message
        });
    }
    
    next(error);
};

// Debugging middleware for create cut
router.post('/', authenticateToken, upload.single('video'), handleMulterError, (req, res, next) => {
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Create cut request received`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] User: ${req.user._id}`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Headers:`, req.headers);
    
    if (req.file) {
        console.log(`🎬 [CREATE CUT ROUTE DEBUG] Video file:`, {
            originalname: req.file.originalname,
            mimetype: req.file.mimetype,
            size: req.file.size
        });
    } else {
        console.log(`❌ [CREATE CUT ROUTE DEBUG] No video file received`);
    }
    
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Body fields:`, Object.keys(req.body));
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] User ID: "${req.body.user_id}"`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Title: "${req.body.title}"`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Description: "${req.body.description}"`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Visibility: "${req.body.visibility}"`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Interests: "${req.body.interests}"`);
    console.log(`🎬 [CREATE CUT ROUTE DEBUG] Tags: "${req.body.tags}"`);
    
    next();
}, createCut);

// Public routes (no authentication required)

// Get all cuts with filtering and pagination
router.get('/', getAllCuts);

// Get trending cuts
router.get('/trending', getTrendingCuts);

// Get cuts by interests
router.get('/interests/:interests', getCutsByInterests);

// Get cuts by user ID
router.get('/user/:userId', getCutsByUser);

// Get cut by ID
router.get('/:cutId', getCutById);

// Protected routes (authentication required)

// Update cut
router.put('/:cutId', authenticateToken, updateCut);

// Delete cut
router.delete('/:cutId', authenticateToken, deleteCut);

// Like/Unlike cut
router.post('/:cutId/like', authenticateToken, toggleLike);

// Add comment to cut
router.post('/:cutId/comment', authenticateToken, addComment);

// Share cut
router.post('/:cutId/share', authenticateToken, shareCut);

module.exports = router;
