const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const {
    getRecentMessages,
    sendMessage,
    editMessage,
    deleteMessage,
    addReaction,
    searchMessages
} = require('../controllers/groupMessageController');

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

const fileFilter = (req, file, cb) => {
    console.log(`💬 [UPLOAD DEBUG] File received: ${file.originalname}`);
    console.log(`💬 [UPLOAD DEBUG] MIME type: ${file.mimetype}`);
    
    // Allow all image and video types
    const allowedImageTypes = [
        'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 
        'image/bmp', 'image/tiff', 'image/svg+xml'
    ];
    
    const allowedVideoTypes = [
        'video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv', 
        'video/webm', 'video/mkv', 'video/m4v', 'video/quicktime'
    ];
    
    const allowedFileTypes = [
        'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain', 'text/csv'
    ];
    
    const allAllowedTypes = [...allowedImageTypes, ...allowedVideoTypes, ...allowedFileTypes];
    
    // Check MIME type
    if (allAllowedTypes.includes(file.mimetype)) {
        console.log(`✅ [UPLOAD DEBUG] File type allowed: ${file.mimetype}`);
        return cb(null, true);
    }
    
    // Check file extension for cases where MIME type might be generic
    const fileExtension = path.extname(file.originalname).toLowerCase();
    const allowedExtensions = [
        '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tiff', '.svg',
        '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v',
        '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt', '.csv'
    ];
    
    if (allowedExtensions.includes(fileExtension)) {
        console.log(`✅ [UPLOAD DEBUG] File extension allowed: ${fileExtension}`);
        return cb(null, true);
    }
    
    console.log(`❌ [UPLOAD DEBUG] File type not allowed: ${file.mimetype} (${fileExtension})`);
    cb(new Error('Invalid file type. Only images, videos, and documents are allowed.'), false);
};

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

// Middleware to handle multer errors
const handleMulterError = (error, req, res, next) => {
    if (error instanceof multer.MulterError) {
        if (error.code === 'LIMIT_FILE_SIZE') {
            return res.status(400).json({
                success: false,
                message: 'File too large. Maximum size is 100MB.'
            });
        }
        if (error.code === 'LIMIT_FILE_COUNT') {
            return res.status(400).json({
                success: false,
                message: 'Too many files. Only one file per message is allowed.'
            });
        }
        if (error.code === 'LIMIT_UNEXPECTED_FILE') {
            return res.status(400).json({
                success: false,
                message: 'Unexpected file field. Use "media" field for file uploads.'
            });
        }
    }
    
    if (error.message.includes('Invalid file type')) {
        return res.status(400).json({
            success: false,
            message: error.message
        });
    }
    
    next(error);
};

// Public routes (no authentication required for now)

// Get recent messages for a group
router.get('/:groupId/messages', getRecentMessages);

// Search messages in a group
router.get('/:groupId/search', searchMessages);

// Send a message to group (with optional media upload)
router.post('/:groupId/send', upload.single('media'), handleMulterError, sendMessage);

// Edit a message
router.put('/message/:messageId/edit', editMessage);

// Delete a message
router.delete('/message/:messageId', deleteMessage);

// Add reaction to message
router.post('/message/:messageId/reaction', addReaction);

module.exports = router;
