const express = require('express');
const router = express.Router();
const multer = require('multer');
const { register, login, verifyOTP, resendOTP, getAllUsers, getUserByMobile, getUserById, getUserCompletionStatus, createOrUpdateOccupation, getOccupation, deleteOccupation, getUserTabs, uploadProfileImage, getProfileImage, deleteProfileImage, updateProfileImage, getProfessionStatus, updateProfessionStatus, getSchoolDetails, updateSchoolDetails, getCollegeDetails, updateCollegeDetails, getUserAbout, updateUserAbout, getUserInterests, updateUserInterests, getUserAboutAndInterests, updateWorkingProfessionalDetails, updateBusinessDetails } = require('../controllers/userController');
const { validateRegistration, validateOTP } = require('../middleware/validation');
// const { validatePasswordStrength, requestSizeLimiter } = require('../middleware/security'); // Removed for testing
const { authenticateToken } = require('../middleware/auth');

// Configure multer for profile image uploads
const storage = multer.memoryStorage();
const upload = multer({
    storage: storage,
    limits: {
        fileSize: 10 * 1024 * 1024, // 10MB limit
    },
    fileFilter: (req, file, cb) => {
        console.log(`🔍 [MULTER FILE FILTER DEBUG] File details:`, {
            originalname: file.originalname,
            mimetype: file.mimetype,
            fieldname: file.fieldname,
            encoding: file.encoding
        });
        
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        
        // Check MIME type
        if (allowedTypes.includes(file.mimetype)) {
            console.log(`✅ [MULTER FILE FILTER DEBUG] MIME type accepted: ${file.mimetype}`);
            cb(null, true);
        } else {
            // Also check file extension as fallback
            const ext = file.originalname.toLowerCase().split('.').pop();
            const allowedExtensions = ['jpg', 'jpeg', 'png', 'webp'];
            
            console.log(`🔍 [MULTER FILE FILTER DEBUG] MIME type rejected: ${file.mimetype}, checking extension: ${ext}`);
            
            if (allowedExtensions.includes(ext)) {
                console.log(`✅ [MULTER FILE FILTER DEBUG] File extension accepted: ${ext}`);
                cb(null, true);
            } else {
                console.log(`❌ [MULTER FILE FILTER DEBUG] Both MIME type and extension rejected`);
                cb(new Error(`Invalid file type. Only JPEG, PNG, and WebP images are allowed. Received: ${file.mimetype} (${ext})`), false);
            }
        }
    }
});

// Multer error handling middleware
const handleMulterError = (err, req, res, next) => {
    if (err instanceof multer.MulterError) {
        console.error('❌ [MULTER ERROR] Multer error:', err);
        return res.status(400).json({
            success: false,
            message: 'File upload error',
            error: err.message
        });
    } else if (err) {
        console.error('❌ [MULTER ERROR] Other error:', err);
        return res.status(400).json({
            success: false,
            message: err.message || 'File upload error'
        });
    }
    next();
};

// Registration routes with security middlewares
router.post('/register', 
    register
);

// Login route
router.post('/login', 
    login
);

router.post('/verify-otp', 
    validateOTP,
    verifyOTP
);

router.post('/resend-otp', 
    resendOTP
);

// Get current user information
router.get('/', 
    authenticateToken,
    (req, res) => {
        // Return current user information from the token
        res.json({
            success: true,
            message: 'Current user retrieved successfully',
            data: {
                user: {
                    _id: req.user._id,
                    name: req.user.name,
                    mobile: req.user.mobile,
                    email: req.user.email,
                    profileImage: req.user.profileImage,
                    occupation: req.user.occupation,
                    profession_status: req.user.profession_status,
                    schoolDetails: req.user.schoolDetails,
                    collegeDetails: req.user.collegeDetails,
                    hasPersonalDetails: req.user.hasPersonalDetails,
                    personalDetailsCompleted: req.user.personalDetailsCompleted,
                    occupationCompleted: req.user.occupationCompleted,
                    hasOccupation: req.user.hasOccupation,
                    createdAt: req.user.createdAt,
                    updatedAt: req.user.updatedAt
                }
            }
        });
    }
);

// Get current user's occupation status
router.get('/occupation-status', 
    authenticateToken,
    (req, res) => {
        // Return current user's occupation information
        res.json({
            success: true,
            message: 'User occupation status retrieved successfully',
            data: {
                user: {
                    _id: req.user._id,
                    name: req.user.name,
                    mobile: req.user.mobile,
                    occupation: req.user.occupation,
                    profession_status: req.user.profession_status,
                    occupationCompleted: req.user.occupationCompleted,
                    hasOccupation: req.user.hasOccupation
                }
            }
        });
    }
);

// Testing routes (for development/testing purposes) - protected
router.get('/all', 
    authenticateToken,
    getAllUsers
);

router.get('/mobile/:mobile', 
    authenticateToken,
    getUserByMobile
);

// User completion status route (must come before /:userId)
router.get('/completion-status', 
    authenticateToken,
    getUserCompletionStatus
);

// Get user by ID (must come after specific routes)
router.get('/:userId', 
    authenticateToken,
    getUserById
);

// Occupation routes
router.post('/occupation', 
    authenticateToken,
    createOrUpdateOccupation
);

router.get('/occupation', 
    authenticateToken,
    getOccupation
);

router.delete('/occupation', 
    authenticateToken,
    deleteOccupation
);

// Get user tabs based on occupation
router.get('/tabs', 
    authenticateToken,
    getUserTabs
);

// Debug route for testing file uploads (remove in production)
router.post('/debug-upload', 
    upload.single('profileImage'),
    (req, res) => {
        console.log(`🔍 [DEBUG UPLOAD] Request received`);
        console.log(`🔍 [DEBUG UPLOAD] Body:`, req.body);
        console.log(`🔍 [DEBUG UPLOAD] File:`, req.file);
        console.log(`🔍 [DEBUG UPLOAD] Headers:`, req.headers);
        
        res.json({
            success: true,
            message: 'Debug upload received',
            data: {
                body: req.body,
                file: req.file ? {
                    originalname: req.file.originalname,
                    mimetype: req.file.mimetype,
                    size: req.file.size,
                    fieldname: req.file.fieldname
                } : null,
                headers: {
                    'content-type': req.headers['content-type'],
                    'content-length': req.headers['content-length']
                }
            }
        });
    }
);

// Profile image routes
router.post('/profile-image/:userId', 
    authenticateToken,
    upload.single('profileImage'),
    handleMulterError,
    uploadProfileImage
);

router.put('/profile-image/:userId', 
    authenticateToken,
    upload.single('profileImage'),
    handleMulterError,
    updateProfileImage
);

router.get('/profile-image/:userId', 
    authenticateToken,
    getProfileImage
);

router.delete('/profile-image/:userId', 
    authenticateToken,
    deleteProfileImage
);

// Profession status routes
router.get('/profession-status/:userId', 
    getProfessionStatus
);

router.put('/profession-status/:userId', 
    authenticateToken,
    updateProfessionStatus
);

// School details routes
router.get('/school-details/:userId', 
    getSchoolDetails
);

router.put('/school-details/:userId', 
    authenticateToken,
    updateSchoolDetails
);

// College details routes
router.get('/college-details/:userId', 
    getCollegeDetails
);

router.put('/college-details/:userId', 
    authenticateToken,
    updateCollegeDetails
);

// User about routes
router.get('/about/:userId', 
    getUserAbout
);

router.put('/about/:userId', 
    authenticateToken,
    updateUserAbout
);

// User interests routes
router.get('/interests/:userId', 
    getUserInterests
);

router.put('/interests/:userId', 
    authenticateToken,
    updateUserInterests
);

// Combined about and interests route
router.get('/about-interests/:userId', 
    getUserAboutAndInterests
);

// Working Professional Details routes
router.put('/working-professional/:userId', 
    authenticateToken,
    updateWorkingProfessionalDetails
);

// Business Details routes
router.put('/business/:userId', 
    authenticateToken,
    updateBusinessDetails
);

// Get user completion status and all flags
router.get('/completion-status/:userId', 
    authenticateToken,
    async (req, res) => {
        try {
            const { userId } = req.params;
            const User = require('../models/User');
            
            console.log(`📊 [COMPLETION STATUS DEBUG] Getting completion status for userId: ${userId}`);
            
            const user = await User.findById(userId).select(
                'name mobile hasOccupation occupation hasPersonalDetails personalDetailsCompleted occupationCompleted profession_status schoolDetails collegeDetails about interests'
            );
            
            if (!user) {
                console.log(`❌ [COMPLETION STATUS DEBUG] User not found: ${userId}`);
                return res.status(404).json({
                    success: false,
                    message: 'User not found'
                });
            }
            
            console.log(`✅ [COMPLETION STATUS DEBUG] User found:`, {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                hasOccupation: user.hasOccupation,
                occupation: user.occupation,
                hasPersonalDetails: user.hasPersonalDetails,
                personalDetailsCompleted: user.personalDetailsCompleted,
                occupationCompleted: user.occupationCompleted,
                profession_status: user.profession_status,
                hasSchoolDetails: !!user.schoolDetails,
                hasCollegeDetails: !!user.collegeDetails,
                hasAbout: !!user.about,
                interestsCount: user.interests?.length || 0
            });
            
            res.json({
                success: true,
                message: 'User completion status retrieved successfully',
                data: {
                    userId: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    hasOccupation: user.hasOccupation,
                    occupation: user.occupation,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted,
                    occupationCompleted: user.occupationCompleted,
                    profession_status: user.profession_status,
                    schoolDetails: user.schoolDetails,
                    collegeDetails: user.collegeDetails,
                    about: user.about,
                    interests: user.interests,
                    completionSummary: {
                        hasOccupation: user.hasOccupation,
                        occupation: user.occupation,
                        hasPersonalDetails: user.hasPersonalDetails,
                        personalDetailsCompleted: user.personalDetailsCompleted,
                        occupationCompleted: user.occupationCompleted,
                        hasSchoolDetails: !!user.schoolDetails,
                        hasCollegeDetails: !!user.collegeDetails,
                        hasAbout: !!user.about,
                        interestsCount: user.interests?.length || 0
                    }
                }
            });
            
        } catch (error) {
            console.error('❌ [COMPLETION STATUS ERROR] Get completion status failed:', error);
            res.status(500).json({
                success: false,
                message: 'Failed to get completion status',
                error: error.message
            });
        }
    }
);

// Get complete user profile details by userId (SINGLE API FOR ALL DETAILS)
router.get('/profile-details/:userId', 
    authenticateToken,
    async (req, res) => {
        try {
            const { userId } = req.params;
            const User = require('../models/User');
            
            console.log(`👤 [PROFILE DETAILS DEBUG] Getting complete profile details for userId: ${userId}`);
            
            // Fetch all user details in one query
            const user = await User.findById(userId).select(
                'name mobile email dob gender emailId bloodGroup pincodeNative state district nativePlace nameMeaning referralCode referredBy ' +
                'hasOccupation occupation hasPersonalDetails personalDetailsCompleted occupationCompleted profession_status ' +
                'schoolDetails collegeDetails about interests profileImage workingProfessional business ' +
                'isVerified createdAt updatedAt'
            );
            
            if (!user) {
                console.log(`❌ [PROFILE DETAILS DEBUG] User not found: ${userId}`);
                return res.status(404).json({
                    success: false,
                    message: 'User not found'
                });
            }
            
            console.log(`✅ [PROFILE DETAILS DEBUG] User found:`, {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                hasOccupation: user.hasOccupation,
                occupation: user.occupation,
                hasPersonalDetails: user.hasPersonalDetails,
                personalDetailsCompleted: user.personalDetailsCompleted,
                occupationCompleted: user.occupationCompleted,
                profession_status: user.profession_status,
                hasSchoolDetails: !!user.schoolDetails,
                hasCollegeDetails: !!user.collegeDetails,
                hasAbout: !!user.about,
                interestsCount: user.interests?.length || 0,
                hasProfileImage: !!user.profileImage
            });
            
            // Generate profile image URL if exists
            const profileImageUrl = user.profileImage 
                ? `http://135.181.103.182:5500/uploads/profiles/${user.profileImage}`
                : null;
            
            res.json({
                success: true,
                message: 'Complete user profile details retrieved successfully',
                data: {
                    // Basic Info
                    userId: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    email: user.email,
                    dob: user.dob,
                    gender: user.gender,
                    emailId: user.emailId,
                    bloodGroup: user.bloodGroup,
                    
                    // Location Info
                    pincodeNative: user.pincodeNative,
                    state: user.state,
                    district: user.district,
                    nativePlace: user.nativePlace,
                    nameMeaning: user.nameMeaning,
                    
                    // Referral Info
                    referralCode: user.referralCode,
                    referredBy: user.referredBy,
                    
                    // Occupation Info
                    hasOccupation: user.hasOccupation,
                    occupation: user.occupation,
                    occupationCompleted: user.occupationCompleted,
                    
                    // Personal Details Info
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted,
                    profession_status: user.profession_status,
                    
                    // School Details
                    schoolDetails: user.schoolDetails || null,
                    
                    // College Details
                    collegeDetails: user.collegeDetails || null,
                    
                    // Working Professional Details
                    workingProfessional: user.workingProfessional || null,
                    
                    // Business Details
                    business: user.business || null,
                    
                    // About & Interests
                    about: user.about || '',
                    interests: user.interests || [],
                    
                    // Profile Image
                    profileImage: user.profileImage,
                    profileImageUrl: profileImageUrl,
                    
                    // Status & Timestamps
                    isVerified: user.isVerified,
                    createdAt: user.createdAt,
                    updatedAt: user.updatedAt,
                    
                    // Completion Summary
                    completionSummary: {
                        hasOccupation: user.hasOccupation,
                        occupation: user.occupation,
                        hasPersonalDetails: user.hasPersonalDetails,
                        personalDetailsCompleted: user.personalDetailsCompleted,
                        occupationCompleted: user.occupationCompleted,
                        hasSchoolDetails: !!user.schoolDetails,
                        hasCollegeDetails: !!user.collegeDetails,
                        hasWorkingProfessionalDetails: !!user.workingProfessional,
                        hasBusinessDetails: !!user.business,
                        hasAbout: !!user.about,
                        interestsCount: user.interests?.length || 0,
                        hasProfileImage: !!user.profileImage,
                        hasLocation: !!(user.state && user.district),
                        hasReferralInfo: !!user.referralCode
                    }
                }
            });
            
        } catch (error) {
            console.error('❌ [PROFILE DETAILS ERROR] Get profile details failed:', error);
            res.status(500).json({
                success: false,
                message: 'Failed to get profile details',
                error: error.message
            });
        }
    }
);

module.exports = router;
