const errorHandler = (err, req, res, next) => {
    console.error('Error:', err);
    console.error('Error code:', err.code);
    console.error('Error message:', err.message);
    console.error('Error stack:', err.stack);
    
    if (err.code === 'ER_DUP_ENTRY') {
        return res.status(409).json({
            success: false,
            message: 'Duplicate entry. This record already exists.',
            error: err.message
        });
    }
    
    if (err.code === 'ER_NO_REFERENCED_ROW_2') {
        return res.status(400).json({
            success: false,
            message: 'Referenced record does not exist.',
            error: err.message
        });
    }
    
    // Handle database connection errors
    if (err.code === 'ECONNREFUSED' || err.code === 'ER_ACCESS_DENIED_ERROR' || err.code === 'ER_BAD_DB_ERROR') {
        return res.status(500).json({
            success: false,
            message: 'Database connection error. Please check your database configuration.',
            error: process.env.NODE_ENV === 'development' ? err.message : undefined
        });
    }
    
    // Handle table not found errors
    if (err.code === 'ER_NO_SUCH_TABLE') {
        return res.status(500).json({
            success: false,
            message: 'Database table not found. Please ensure the database schema is properly set up.',
            error: process.env.NODE_ENV === 'development' ? err.message : undefined
        });
    }
    
    res.status(err.status || 500).json({
        success: false,
        message: err.message || 'Internal server error',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined,
        errorCode: process.env.NODE_ENV === 'development' ? err.code : undefined
    });
};

module.exports = errorHandler;

