const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Import controllers
const {
    createPost,
    getAllPosts,
    getPostById,
    updatePost,
    deletePost,
    toggleLike,
    addComment,
    sharePost,
    getUserPosts,
    getUserPostCount,
    getPostStats,
    getPostsByInterests
} = require('../controllers/postController');

// Import middleware
const { authenticateToken } = require('../middleware/auth');
const { validatePostCreation } = require('../middleware/validation');

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

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

// File filter for images and videos
const fileFilter = (req, file, cb) => {
    console.log(`🔍 [FILE FILTER DEBUG] Checking file: ${file.originalname}`);
    console.log(`🔍 [FILE FILTER DEBUG] MIME type: ${file.mimetype}`);
    console.log(`🔍 [FILE FILTER DEBUG] Field name: ${file.fieldname}`);
    console.log(`🔍 [FILE FILTER DEBUG] File size: ${file.size} bytes`);
    
    const allowedTypes = [
        // Common image formats
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/gif',
        'image/webp',
        'image/bmp',
        'image/tiff',
        'image/tif',
        'image/svg+xml',
        'image/ico',
        'image/icon',
        'image/x-icon',
        'image/vnd.microsoft.icon',
        'image/heic',
        'image/heif',
        'image/avif',
        'image/jxl',
        'image/raw',
        'image/cr2',
        'image/nef',
        'image/arw',
        'image/dng',
        'image/psd',
        'image/ai',
        'image/eps',
        'image/pdf',
        // Video formats
        'video/mp4',
        'video/avi',
        'video/mov',
        'video/wmv',
        'video/flv',
        'video/webm',
        'video/mkv',
        'video/3gp',
        'video/ogv',
        'video/m4v',
        'video/quicktime',
        // Additional common types that might be sent from Flutter
        'image/*',
        'video/*',
        'application/octet-stream', // Sometimes sent for unknown types
        'multipart/form-data'
    ];

    // More permissive check - allow any image or video type
    const isImage = file.mimetype.startsWith('image/');
    const isVideo = file.mimetype.startsWith('video/');
    const isAllowedType = allowedTypes.includes(file.mimetype);
    const isGenericBinary = file.mimetype === 'application/octet-stream';
    const hasImageExtension = /\.(jpg|jpeg|png|gif|webp|bmp|tiff|svg)$/i.test(file.originalname);
    const hasVideoExtension = /\.(mp4|avi|mov|wmv|flv|webm|mkv|3gp|ogv|m4v)$/i.test(file.originalname);
    
    console.log(`🔍 [FILE FILTER DEBUG] Is image: ${isImage}`);
    console.log(`🔍 [FILE FILTER DEBUG] Is video: ${isVideo}`);
    console.log(`🔍 [FILE FILTER DEBUG] Is allowed type: ${isAllowedType}`);
    console.log(`🔍 [FILE FILTER DEBUG] Is generic binary: ${isGenericBinary}`);
    console.log(`🔍 [FILE FILTER DEBUG] Has image extension: ${hasImageExtension}`);
    console.log(`🔍 [FILE FILTER DEBUG] Has video extension: ${hasVideoExtension}`);

    if (isImage || isVideo || isAllowedType || (isGenericBinary && (hasImageExtension || hasVideoExtension))) {
        console.log(`✅ [FILE FILTER DEBUG] File accepted: ${file.originalname}`);
        cb(null, true);
    } else {
        console.log(`❌ [FILE FILTER DEBUG] File rejected: ${file.originalname} (${file.mimetype})`);
        console.log(`❌ [FILE FILTER DEBUG] Allowed types: ${allowedTypes.join(', ')}`);
        cb(new Error(`Invalid file type: ${file.mimetype}. Only images and videos are allowed.`), false);
    }
};

// Configure multer
const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 50 * 1024 * 1024, // 50MB limit per file
        files: 10, // Maximum 10 files per request
        fieldSize: 10 * 1024 * 1024 // 10MB for text fields
    },
    onError: (err, next) => {
        console.log(`❌ [MULTER ERROR] Multer error occurred:`, err);
        next(err);
    }
});

// Public routes (no authentication required)
router.get('/', getAllPosts); // Get all posts with pagination and filtering
router.get('/stats', getPostStats); // Get post statistics
router.get('/interests/:interests', getPostsByInterests); // Get posts by interests
router.get('/user/:userId', getUserPosts); // Get user's posts
router.get('/user/:userId/count', getUserPostCount); // Get user's post count

// Protected routes (authentication required)
router.post('/', 
    (req, res, next) => {
        console.log(`🚀 [ROUTE DEBUG] POST /api/posts - Request received`);
        console.log(`🚀 [ROUTE DEBUG] Content-Type: ${req.headers['content-type']}`);
        console.log(`🚀 [ROUTE DEBUG] Content-Length: ${req.headers['content-length']}`);
        console.log(`🚀 [ROUTE DEBUG] User-Agent: ${req.headers['user-agent']}`);
        next();
    },
    authenticateToken,
    (req, res, next) => {
        console.log(`🔐 [AUTH DEBUG] Authentication passed for user: ${req.user?._id}`);
        next();
    },
    upload.array('media', 10), // Allow up to 10 files
    (req, res, next) => {
        console.log(`📁 [UPLOAD DEBUG] Files received: ${req.files?.length || 0}`);
        if (req.files && req.files.length > 0) {
            req.files.forEach((file, index) => {
                console.log(`📁 [UPLOAD DEBUG] File ${index + 1}: ${file.originalname} (${file.mimetype})`);
            });
        }
        console.log(`📝 [UPLOAD DEBUG] Body fields:`, Object.keys(req.body));
        next();
    },
    validatePostCreation,
    createPost
);

router.put('/:id', 
    (req, res, next) => {
        console.log(`🔄 [UPDATE ROUTE DEBUG] PUT /api/posts/${req.params.id} - Request received`);
        console.log(`🔄 [UPDATE ROUTE DEBUG] Content-Type: ${req.headers['content-type']}`);
        console.log(`🔄 [UPDATE ROUTE DEBUG] Content-Length: ${req.headers['content-length']}`);
        next();
    },
    authenticateToken,
    (req, res, next) => {
        console.log(`🔐 [UPDATE AUTH DEBUG] Authentication passed for user: ${req.user?._id}`);
        next();
    },
    upload.array('media', 10), // Allow up to 10 files for updates
    (req, res, next) => {
        console.log(`📁 [UPDATE UPLOAD DEBUG] Files received: ${req.files?.length || 0}`);
        if (req.files && req.files.length > 0) {
            req.files.forEach((file, index) => {
                console.log(`📁 [UPDATE UPLOAD DEBUG] File ${index + 1}: ${file.originalname} (${file.mimetype})`);
            });
        }
        console.log(`📝 [UPDATE UPLOAD DEBUG] Body fields:`, Object.keys(req.body));
        next();
    },
    updatePost
);

// Get single post by ID (moved after PUT to avoid route conflicts)
router.get('/:id', getPostById);

router.delete('/:id', 
    authenticateToken,
    deletePost
);

router.post('/:id/like', 
    authenticateToken,
    toggleLike
);

router.post('/:id/comment', 
    authenticateToken,
    addComment
);

router.post('/:id/share', 
    authenticateToken,
    sharePost
);

// Error handling middleware for multer
router.use((error, req, res, next) => {
    console.log(`❌ [ERROR HANDLER] Error occurred:`, {
        message: error.message,
        code: error.code,
        name: error.name,
        stack: error.stack
    });
    
    if (error instanceof multer.MulterError) {
        console.log(`❌ [MULTER ERROR] Multer error: ${error.code}`);
        
        if (error.code === 'LIMIT_FILE_SIZE') {
            return res.status(400).json({
                success: false,
                message: 'File too large. Maximum size is 50MB.'
            });
        }
        if (error.code === 'LIMIT_FILE_COUNT') {
            return res.status(400).json({
                success: false,
                message: 'Too many files. Maximum 10 files allowed.'
            });
        }
        if (error.code === 'LIMIT_UNEXPECTED_FILE') {
            return res.status(400).json({
                success: false,
                message: 'Unexpected field name for file upload.'
            });
        }
    }
    
    if (error.message && error.message.includes('Invalid file type')) {
        console.log(`❌ [FILE TYPE ERROR] File type rejected: ${error.message}`);
        return res.status(400).json({
            success: false,
            message: error.message
        });
    }
    
    console.log(`❌ [UNHANDLED ERROR] Passing error to next handler`);
    next(error);
});

module.exports = router;
