// const express = require('express');
// const router = express.Router();
// const auth = require('../middlewares/authMiddleware');
// const { saveMessage, getMessages } = require('../controllers/chatController');

// router.post('/', auth, saveMessage);
// router.get('/:meetingId', auth, getMessages);

// module.exports = router;
// routes/chat.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { uploadFile, getChatMessages, saveTextMessage } = require('../controllers/chatController');
// const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// Ensure upload directory exists
const uploadDir = path.join(__dirname, '../uploads/chat');
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// Configure multer for local storage
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        // Generate unique filename with timestamp
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const fileExtension = path.extname(file.originalname);
        const fileName = `${file.fieldname}-${uniqueSuffix}${fileExtension}`;
        cb(null, fileName);
    }
});

// File filter for allowed types
const fileFilter = (req, file, cb) => {
    console.log('📋 Checking file type:', file.mimetype);

    const allowedTypes = [
        // Images
        'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
        // Videos
        'video/mp4', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/avi',
        // Documents
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'text/plain',
        'text/csv',
        // Archives
        'application/zip',
        'application/x-rar-compressed',
        'application/x-7z-compressed'
    ];

    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(new Error(`File type ${file.mimetype} not allowed`), false);
    }
};

// Configure multer upload
const upload = multer({
    storage: storage,
    limits: {
        fileSize: 25 * 1024 * 1024, // 25MB limit
        files: 1 // Single file upload
    },
    fileFilter: fileFilter
});

// File upload route
router.post('/upload', (req, res, next) => {
    upload.single('file')(req, res, (err) => {
        if (err instanceof multer.MulterError) {
            console.error('Multer error:', err);
            if (err.code === 'LIMIT_FILE_SIZE') {
                return res.status(400).json({
                    success: false,
                    error: 'File too large. Maximum size is 25MB.'
                });
            }
            return res.status(400).json({
                success: false,
                error: 'Upload error: ' + err.message
            });
        } else if (err) {
            console.error('Upload error:', err);
            return res.status(400).json({
                success: false,
                error: err.message
            });
        }
        next();
    });
}, uploadFile);

// Get chat messages
router.get('/messages/:meetingId', getChatMessages);
router.post('/text', saveTextMessage)
// Health check route
router.get('/health', (req, res) => {
    res.json({
        success: true,
        message: 'Chat API is running',
        uploadDir: uploadDir,
        timestamp: new Date().toISOString()
    });
});

module.exports = router;
