const User = require('../models/User');
const PersonalDetails = require('../models/PersonalDetails');

// Login user
exports.login = async (req, res) => {
    try {
      

        const { mobile, password } = req.body;
     
        // Validate required fields
        if (!mobile || !password) {
            console.log('❌ Validation failed - missing required fields');
            console.log('Mobile truthy?', !!mobile);
            console.log('Password truthy?', !!password);
            return res.status(400).json({
                success: false,
                message: 'Mobile number and password are required',
                debug: {
                    mobile: {
                        provided: !!mobile,
                        value: mobile,
                        type: typeof mobile
                    },
                    password: {
                        provided: !!password,
                        type: typeof password
                    }
                }
            });
        }

      
        const normalizedMobile = mobile.toString().trim();
        
  
        const user = await User.findOne({ mobile: normalizedMobile });
        
        if (!user) {
            console.log('❌ User not found for mobile:', normalizedMobile);
            return res.status(401).json({
                success: false,
                message: 'Account Not Found',
                debug: {
                    searchedMobile: normalizedMobile
                }
            });
        }


        const passwordMatch = user.verifyPassword(password);
     
        if (!passwordMatch) {
            console.log('❌ Password verification failed');
            return res.status(401).json({
                success: false,
                message: 'Invalid mobile number or password'
            });
        }

        const token = user.generateToken();
        
        // Check if personal details are completed
        const personalDetails = await PersonalDetails.findOne({ userId: user._id });
        
        res.json({
            success: true,
            message: 'Login successful',
            data: {
                user: {
                    id: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    dob: user.dob,
                    isVerified: user.isVerified,
                    hasPersonalDetails: user.hasPersonalDetails,
                    hasOccupation: user.hasOccupation,
                    personalDetailsCompleted: user.personalDetailsCompleted,
                    occupationCompleted: user.occupationCompleted,
                    occupation: user.occupation
                },
                token
            }
        });

    } catch (error) {
       
        
        res.status(500).json({
            success: false,
            message: 'Login failed',
            error: error.message,
            debug: {
                errorType: error.name,
                timestamp: new Date().toISOString()
            }
        });
    }
};

// Get user profile by ID
exports.getProfile = async (req, res) => {
    try {
        const userId = req.params.userId;
        const user = await User.findById(userId).select('-password -otp');
        
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // User object already contains occupation and completion status
        const userWithStatus = {
            ...user.toObject(),
            hasPersonalDetails: user.hasPersonalDetails,
            hasOccupation: user.hasOccupation,
            personalDetailsCompleted: user.personalDetailsCompleted,
            occupationCompleted: user.occupationCompleted,
            occupation: user.occupation
        };

        res.json({
            success: true,
            data: userWithStatus
        });
    } catch (error) {
        console.error('Get profile error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get profile',
            error: error.message
        });
    }
};