// middlewares/authMiddleware.js
import jwt from 'jsonwebtoken';
import userModel from '../models/userModel.js';

export async function verifyUser(req, res, next) {
    try {
        const token = req.cookies.userToken || req.headers.authorization?.split(' ')[1];

        if (!token) {
            return res.status(401).json({ success: false, message: 'Authentication token missing' });
        }

        // Verify the token
        const decoded = jwt.verify(token, process.env.JWT_SECRET);

        // Find user
        const user = await userModel.findById(decoded.id).select('-password');
        if (!user) {
            return res.status(404).json({ success: false, message: 'User not found' });
        }

        // Attach user data to request
        req.user = user;
        next();
    } catch (err) {
        console.error('Auth Error:', err.message);
        if (err.name === 'TokenExpiredError') {
            return res.status(401).json({ success: false, message: 'Session expired. Please log in again.' });
        }
        res.status(401).json({ success: false, message: 'Invalid or expired token' });
    }
}
